Typed functional programming in TypeScript TypeScript 中的类型化函数式编程
fp-ts provides developers with popular patterns and reliable abstractions from typed functional languages in TypeScript. fp-ts 为开发人员提供了 TypeScript 中类型化函数语言的流行模式和可靠抽象。
Disclaimer. Teaching functional programming is out of scope of this project, so the documentation assumes you already know what FP is. 免责声明。教授函数式编程超出了本项目的范围,因此文档假设您已经知道 FP 是什么。
Core Concepts 核心概念
The goal of fp-ts is to empower developers to write pure FP apps and libraries built atop higher order abstractions. It includes the most popular data types, type classes, and abstractions from languages like Haskell, PureScript, and Scala. fp-ts 的目标是使开发人员能够编写构建在高阶抽象之上的纯 FP 应用程序和库。它包括最流行的数据类型、类型类以及 Haskell、PureScript 和 Scala 等语言的抽象。
Functions 功能
Functional programming is all about pure functions and how to compose them into bigger structures. fp-ts provides a few general functions to support you with composition, constant functions, and more. 函数式编程都是关于纯函数以及如何将它们组合成更大的结构。 fp-ts 提供了一些通用函数来支持您的组合、常量函数等。
Data Types 数据类型
Data types are the practical part of fp-ts: you can instantiate them with your data to gain properties and functionality that are useful for solving a specific need. Because data types all share common interfaces (through type classes), once you learn how to use one data type, you can apply the same concepts to the others. 数据类型是 fp-ts 的实用部分:您可以使用数据实例化它们,以获得有助于解决特定需求的属性和功能。由于数据类型都共享公共接口(通过类型类),因此一旦您学习了如何使用一种数据类型,您就可以将相同的概念应用于其他数据类型。
Many functions in fp-ts use ad hoc polymorphism, meaning that they have a single implementation that can deal with arguments of different types. To make this work, it is often necessary to provide a data type instance that provides functionality that is specific to the data type. fp-ts 中的许多函数使用临时多态性,这意味着它们有一个可以处理不同类型参数的实现。为了实现这一点,通常需要提供一个数据类型实例来提供特定于该数据类型的功能。
Note. Data types are not stack safe and there is no trampolining implementation. But for traversing and sequencing lists there is a stack safe and optimized version in each data types. 笔记。数据类型不是堆栈安全的,并且没有蹦床实现。但对于遍历和排序列表,每种数据类型都有一个堆栈安全和优化的版本。
Type Classes 类型类别
Type classes provide the theoretical underpinnings of fp-ts: they describe what you can do with your data. To guarantee that they can be safely composed, they are built on laws rooted in abstract algebra and category theory. 类型类提供了 fp-ts 的理论基础:它们描述了您可以对数据执行哪些操作。为了保证它们可以安全地组合,它们建立在植根于抽象代数和范畴论的定律之上。
Higher Kinded Types 高等种类
A distinctive feature of fp-ts with respect to other functional libraries is its implementation of Higher Kinded Types, which TypeScript doesn’t support natively. The idea for emulating higher kinded types in TypeScript is based on Lightweight higher-kinded polymorphism. 相对于其他函数库, fp-ts 的一个显着特征是它实现了更高种类的类型,而 TypeScript 本身并不支持这种类型。在 TypeScript 中模拟更高种类类型的想法基于轻量级更高种类多态性。
“fp-ts to the max” (TypeScript port of John De Goes’s “FP to the max” in Scala) “ fp-ts to the max”(John De Goes 在 Scala 中的“FP to the max”的 TypeScript 端口)
fastify-funky - plugin that adds support for returning fp-ts Either and Task entities as handler execution results for fastify web framework fastify-funky - 插件添加了对返回 fp-ts Either 和 Task 实体作为 fastify Web 框架的处理程序执行结果的支持
The definition for type constructors of kind * -> * -> * (e.g. Either) * -> * -> * 类型构造函数的定义(例如 Either )
exportinterfaceFunctor2<FextendsURIS2>{readonlyURI:F// v-- here E is freereadonlymap:<E,A,B>(fa:Kind2<F,E,A>,f:(a:A)=>B)=>Kind2<F,E,B>}
The definition for type constructors that start with kind * -> * -> * but need to be constrained in order to admit an instance (e.g. Validation). 以 * -> * -> * 开头但需要受到约束才能接纳实例的类型构造函数的定义(例如 Validation )。
// this fixes E --vexportinterfaceFunctor2C<FextendsURIS2,E>{readonlyURI:Freadonly_E:E// v-- here E is fixed ---------------vreadonlymap:<A,B>(fa:Kind2<F,E,A>,f:(a:A)=>B)=>Kind2<F,E,B>}
For example, Validation admits a Functor instance only if you provide a Semigroup instance for the failure part 例如,仅当您为失败部分提供 Semigroup 实例时, Validation 才会接纳 Functor 实例
// this fixes E --v v-- here E is fixedconstgetFunctor=<E>(S:Semigroup<E>):Functor2C<"Validation",E>={...}
What an E suffix means, e.g. matchE E 后缀的含义是什么,例如 matchE
E means Effect. An example of its use is in the matchE destructor on monad transformers like TaskOption or ReaderTaskEither. E 表示效果。它的使用示例是 TaskOption 或 ReaderTaskEither 等 monad 转换器上的 matchE 析构函数。
Example 例子
Both of these destructions result in a Task<number>, but in the case of matchE an effect (in this case in the form of a Task) is returned on match. 这两种破坏都会产生 Task<number> ,但在 matchE 的情况下,会在匹配时返回效果(在本例中以 Task 的形式)。
What a K suffix means, e.g. fromEitherK or chainEitherK K 后缀的含义是什么,例如 fromEitherK 或 chainEitherK
K means Kleisli. A Kleisli arrow is a function with the following signature K 表示克莱斯利。 Kleisli 箭头是具有以下签名的函数
(a:A)=>F<B>
where F is a type constructor. 其中 F 是类型构造函数。
Example 例子
Let’s say we have the following parser 假设我们有以下解析器
import*asEfrom'fp-ts/Either'functionparse(s:string):E.Either<Error,number>{constn=parseFloat(s)returnisNaN(n)?E.left(newError(`cannot decode ${JSON.stringify(s)} to number`)):E.right(n)}
and a value of type IOEither<Error, string> 和一个@0类型的值#
We could lift the Kleisli arrow parse, i.e. transform a function 我们可以举起 Kleisli 箭头 parse ,即变换一个函数
(s:string)=>E.Either<Error,number>
into a function 变成一个函数
(s:string)=>IE.IOEither<Error,number>
That’s what fromEitherK is all about 这就是 fromEitherK 的意义所在
import{pipe}from'fp-ts/function'pipe(input,IE.chain(IE.fromEitherK(parse)))()// left(new Error('cannot decode "foo" to number'))// or with less boilerplatepipe(input,IE.chainEitherK(parse))()// left(new Error('cannot decode "foo" to number'))
What a T suffix means, e.g. sequenceT T 后缀的含义是什么,例如 sequenceT
in sequenceT means Tuple, I borrowed the name from the corresponding Haskell function sequenceT 中的意思是Tuple,这个名字我借用了对应的Haskell函数
However usually it means Transformer like in “monad transformers” (e.g. OptionT, EitherT, ReaderT, StateT) 然而,它通常意味着 Transformer,就像“monad 转换器”中的那样(例如 OptionT 、 EitherT 、 ReaderT 、 StateT )
What a W suffix means, e.g. chainW or chainEitherKW W 后缀的含义是什么,例如 chainW 或 chainEitherKW
W means Widen. Functions that end with W are able to aggregate errors into a union (for Either based data types) or environments into an intersection (for Reader based data types). W 表示加宽。以 W 结尾的函数能够将错误聚合到联合(对于基于 Either 的数据类型)或将环境聚合到交集(对于基于 Reader 的数据类型)。
Example 例子
import*asEfrom'fp-ts/Either'import*asTEfrom'fp-ts/TaskEither'import{pipe}from'fp-ts/pipeable'declarefunctionparseString(s:string):E.Either<string,number>declarefunctionfetchUser(id:number):TE.TaskEither<Error,User>// this raises an error because: Type 'string' is not assignable to type 'Error'constprogram_=(s:string)=>pipe(s,TE.fromEitherK(parseString),TE.chain(fetchUser))// const program: (s: string) => TE.TaskEither<string | Error, User>constprogram=(s:string)=>pipe(s,TE.fromEitherK(parseString),TE.chainW(fetchUser))
How to write type class instances for your data type 如何为您的数据类型编写类型类实例
Let’s start from a simple data structure: Identity 让我们从一个简单的数据结构开始: Identity
// Identity.tsexporttypeIdentity<A>=A
Functor instance 函子实例
Let’s see how to add an instance of the Functor type class for Identity 让我们看看如何为 Identity 添加 Functor 类型类的实例
So what’s URItoKind, URIS and Kind? 那么 URItoKind 、 URIS 和 Kind 是什么?
URItoKind is type-level map, it maps a URI to a concrete data type, and is populated using the module augmentation feature URItoKind 是类型级映射,它将 URI 映射到具体数据类型,并使用模块增强功能进行填充
// fp-ts/HKT.tsexportinterfaceURItoKind<A>{}
// Identity.tsdeclaremodule'fp-ts/HKT'{interfaceURItoKind<A>{readonlyIdentity:Identity<A>// maps the key "Identity" to the type `Identity`}}
URIS is just keyof URItoKind<any> and is used as a constraint in the Functor1 interface URIS 只是 keyof URItoKind<any> ,并在 Functor1 接口中用作约束
Kind<F, A> is using URItoKind internally so is able to project an abstract data type to a concrete data type. So if URI = 'Identity', then Kind<URI, number> is Identity<number>. Kind<F, A> 在内部使用 URItoKind ,因此能够将抽象数据类型投影为具体数据类型。所以如果 URI = 'Identity' ,那么 Kind<URI, number> 就是 Identity<number> 。
What about type constructors of kind * -> * -> *? * -> * -> * 类型的类型构造函数怎么样?
There’s another triple for that: URItoKind2, URIS2 and Kind2 还有另一个三元组: URItoKind2 、 URIS2 和 Kind2
Now we can lift double to both Identity and Either 现在我们可以将 double 提升为 Identity 和 Either
// v-- the Functor instance of IdentityconstdoubleIdentity=lift(identity)(double)// v-- the Functor instance of EitherconstdoubleEither=lift(either)(double)
doubleIdentity has type (fa: Identity<number>) => Identity<number> doubleIdentity 的类型为 (fa: Identity<number>) => Identity<number>
doubleEither has type <E>(fa: Either<E, number>) => Either<E, number> doubleEither 的类型为 <E>(fa: Either<E, number>) => Either<E, number>
Migrate from PureScript/Haskell 从 PureScript/Haskell 迁移
This guide shows you how to use fp-ts concepts if you have prior experience with PureScript or Haskell. 如果您之前有使用 PureScript 或 Haskell 的经验,本指南将向您展示如何使用 fp-ts 概念。
maybe :: forall a b. b -> (a -> b) -> Option a -> b
maybe b _ None = b
maybe _ f (Some a) = f a
TypeScript 打字稿
// here TypeScript also provides exhaustiveness checkconstmaybe=<A,B>(onNone:()=>B,onSome:(a:A)=>B)=>(fa:Option<A>):B=>{switch(fa._tag){case'None':returnonNone()case'Some':returnonSome(fa.value)}}
Type classes 类型类别
PureScript 纯脚本
class Functor f where
map :: forall a b. (a -> b) -> f a -> f b
instance semigroupOption :: Semigroup a => Semigroup (Option a) where
append None y = y
append x None = x
append (Some x) (Some y) = Some (x <> y)
instance monoidOption :: Semigroup a => Monoid (Option a) where
mempty = None
TypeScript 打字稿
import{Semigroup}from'fp-ts/Semigroup'import{Monoid}from'fp-ts/Monoid'// ↓ the constraint is implemented as an additional parameterfunctiongetMonoid<A>(S:Semigroup<A>):Monoid<Option<A>>{return{concat:(x,y)=>{if(x._tag==='Some'&&y._tag==='Some'){returnsome(S.concat(x.value,y.value))}elseif(x._tag==='Some'){returny}else{returnx}},empty:none}}
Where’s my f <$> fa <*> fb? 我的 f <$> fa <*> fb 在哪里?
Both Haskell and PureScript languages provide syntactic sugar for working with monads in the form of do notation. Haskell 和 PureScript 语言都以 do 表示法的形式提供了处理 monad 的语法糖。
fp-ts provides it’s own implementation of do notation which can help to simplify effectful code. fp-ts 提供了它自己的 do 表示法的实现,可以帮助简化有效的代码。
Let’s take a look at an example of how do notation can help to simplify our code. Here we have a bit of code which reads two values from the command line, prints them and stores them in an object with x and y properties. 让我们看一个示例,了解 do 表示法如何帮助简化我们的代码。这里我们有一些代码,它从命令行读取两个值,打印它们并将它们存储在具有 x 和 y 属性的对象中。
This will look very familiar to those who have prior experience with Purescript or Haskell where we could write something like: 对于那些有 Purescript 或 Haskell 经验的人来说,这看起来非常熟悉,我们可以编写如下内容:
Note that due to the lack of type-classes in Typescript, when working with fp-ts we need to import everything from the appropriate module. In the previous example, we use specific Do, bind, map and chainFirst functions imported from the Task module as we were working with the Task type. 请注意,由于 Typescript 中缺少类型类,因此在使用 fp-ts 时,我们需要从适当的模块导入所有内容。在前面的示例中,我们使用从 Task 模块导入的特定 Do 、 bind 、 map 和 chainFirst 函数,就像我们使用 Task 类型一样。
If we were to write the same code using the IO monad, we would need to import everything from the IO module like so: 如果我们要使用 IO monad 编写相同的代码,则需要从 IO 模块导入所有内容,如下所示:
IO.Do is just an alias for IO.of({}) where {} is an empty record. IO.Do 只是 IO.of({}) 的别名,其中 {} 是空记录。
You build up a record using bind which accepts a key and a function that accepts the current state of the record and returns an effect of some value to store under the key. 您使用 bind 构建一条记录,它接受一个键和一个函数,该函数接受记录的当前状态并返回某个值的效果以存储在该键下。
The record becomes kind of like a scope to put intermediate values in when you are chaining effects. 当您链接效果时,记录变得有点像放置中间值的范围。
Upgrade to version 2.x 升级到版本2.x
fp-ts@2.x brings with it some major improvements, but also breaking changes and the removal of deprecated APIs. This document will help you understand what changed and how you can upgrade your existing codebase. fp-ts@2.x 带来了一些重大改进,但也带来了重大更改和删除了已弃用的 API。本文档将帮助您了解更改的内容以及如何升级现有代码库。
The major changes in fp-ts@2.x are: fp-ts@2.x 的主要变化是:
Requires TypeScript 3.5+ 需要 TypeScript 3.5+
fp-ts@1.19.x has been released with backported 2.x features for a gradual upgrade path fp-ts@1.19.x 已发布,并带有向后移植的 2.x 功能,用于逐步升级路径
Data types are no longer implemented as classes, resulting in a new API using pipe 数据类型不再作为类实现,从而产生了使用 pipe 的新 API
The run() method on IO, Task, etc. has been replaced with a thunk IO 、 Task 等上的 run() 方法已被替换为thunk
Functions accepting fallback values are now always lazy (e.g. getOrElseL is now just getOrElse) 接受后备值的函数现在总是惰性的(例如 getOrElseL 现在只是 getOrElse )
Deprecations 弃用
HKT: Replaced Type<n> with Kind<n> HKT :将 Type<n> 替换为 Kind<n>
Replaced Setoid with Eq 将 Setoid 替换为 Eq
Several modules were removed, e.g. Exception, Free, StrMap, Trace, Validation, … 删除了几个模块,例如 Exception 、 Free 、 StrMap 、 Trace 、 Validation 、……
Read the full changelog for all the changes 阅读完整的变更日志以了解所有更改
Upgrading from version 1.x 从版本 1.x 升级
You can gradually upgrade your existing codebase using the fp-ts@1.19.x release; the new fp-ts@2.x APIs have been backported to this release. 您可以使用 fp-ts@1.19.x 版本逐步升级现有的代码库;新的 fp-ts@2.x API 已向后移植到此版本。
Upgrade TypeScript to version 3.5+ 将 TypeScript 升级到版本 3.5+
Install fp-ts@1.19.x, which contains the new fp-ts@2.x APIs 安装 fp-ts@1.19.x ,其中包含新的 fp-ts@2.x API
Optional: activate the @obsolete rule for tslint to get guidance on what to change 可选:激活 tslint 的 @obsolete 规则以获取有关更改内容的指导
Gradually replace the existing code with the new API 逐步用新的 API 替换现有代码
Upgrade to fp-ts@2.x and make sure to also upgrade all dependencies that rely on fp-ts 升级到 fp-ts@2.x 并确保也升级依赖于 fp-ts 的所有依赖项
tslint rule tslint 规则
In order to make easier to spot all the occurrences of chainable APIs without depending on @deprecated, which would force you to migrate in one shot, a custom tslint rule is provided (@obsolete). 为了更容易地发现所有可链接 API 的出现,而不依赖于 @deprecated (这会迫使您一次性迁移),提供了一个自定义 tslint 规则 ( @obsolete )。
Add the following lines to your tslint.json to turn the @obsolete rule on: 将以下行添加到 tslint.json 以打开 @obsolete 规则:
This rule is available in the 1.19.x branch. 此规则在 1.19.x 分支中可用。
Dependencies 依赖关系
Don’t forget to update your dependencies: libraries that use fp-ts like io-ts or monocle-ts have to be upgraded to their fp-ts@2.x compatible versions. 不要忘记更新您的依赖项:使用 fp-ts (如 io-ts 或 monocle-ts)的库必须升级到其 fp-ts@2.x 兼容版本。
The new API 新的API
In fp-ts@2.x data types are no longer implemented with classes; the biggest change resulting from this is that the chainable API has been removed. As an alternative, a pipe function is provided, along with suitable data-last top level functions (one for each deprecated method). This is best shown with an example: 在 fp-ts@2.x 中,数据类型不再用类来实现;由此带来的最大变化是可链接 API 已被删除。作为替代方案,提供了 pipe 函数以及合适的 data-last 顶级函数(每个已弃用的方法都有一个)。最好用一个例子来说明这一点:
We recommend to use pipe even if you work with just one function, as it allows TypeScript to infer the types automatically. It’s also easier to migrate existing code, because the argument order remains the same. 即使您只使用一个函数,我们也建议使用 pipe ,因为它允许 TypeScript 自动推断类型。迁移现有代码也更容易,因为参数顺序保持不变。
This section provides technical reference material for the functions, data types, and type classes provided by fp-ts. 本节提供 fp-ts 提供的函数、数据类型和类型类的技术参考资料。
The Alt type class identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *, like Array or Option, rather than concrete types like string or number. Alt 类型类标识类型构造函数上的关联操作。它与 Semigroup 类似,只不过它适用于 * -> * 类型,如 Array 或 Option ,而不是具体类型,如 string 或 number 。
Alt instances are required to satisfy the following laws: Alt 实例需要满足以下定律:
The Alternative type class extends the Alt type class with a value that should be the left and right identity for alt. Alternative 类型类扩展了 Alt 类型类,其值应该是 alt 的左右标识。
It is similar to Monoid, except that it applies to types of kind * -> *, like Array or Option, rather than concrete types like string or number. 它与 Monoid 类似,不同之处在于它适用于 * -> * 类型,如 Array 或 Option ,而不是具体类型,如 string 或 number 。
Alternative instances should satisfy the following laws: Alternative 实例应满足以下规律:
Left identity: A.alt(zero, fa) <-> fa 左身份: A.alt(zero, fa) <-> fa
Right identity: A.alt(fa, zero) <-> fa 正确身份: A.alt(fa, zero) <-> fa
Annihilation: A.map(zero, f) <-> zero 湮灭: A.map(zero, f) <-> zero
The Applicative type class extends the Apply type class with a of function, which can be used to create values of type f a from values of type a. Applicative 类型类使用 of 函数扩展 Apply 类型类,该函数可用于从 a 类型的值创建 f a 类型的值。
Where Apply provides the ability to lift functions of two or more arguments to functions whose arguments are wrapped using f, and Functor provides the ability to lift functions of one argument, pure can be seen as the function which lifts functions of zero arguments. That is, Applicative functors support a lifting operation for any number of function arguments. 其中 Apply 提供了将两个或多个参数的函数提升到使用 f 包装参数的函数的能力,而 Functor 提供了提升一个参数的函数的能力, pure 可以看作是以下函数:提升零参数的函数。也就是说, Applicative 函子支持任意数量的函数参数的提升操作。
Instances must satisfy the following laws in addition to the Apply laws: 除了 Apply 法则之外,实例还必须满足以下法则:
Identity: A.ap(A.of(a => a), fa) <-> fa 身份: A.ap(A.of(a => a), fa) <-> fa
The Apply class provides the ap which is used to apply a function to an argument under a type constructor. Apply 类提供 ap ,用于将函数应用于类型构造函数下的参数。
Apply can be used to lift functions of two or more arguments to work on values wrapped with the type constructor f. Apply 可用于提升两个或多个参数的函数,以处理使用类型构造函数 f 包装的值。
Instances must satisfy the following law in addition to the Functor laws: 除了 Functor 法则之外,实例还必须满足以下法则:
Associative composition: F.ap(F.ap(F.map(fbc, bc => ab => a => bc(ab(a))), fab), fa) <-> F.ap(fbc, F.ap(fab, fa)) 联想组合: F.ap(F.ap(F.map(fbc, bc => ab => a => bc(ab(a))), fab), fa) <-> F.ap(fbc, F.ap(fab, fa))
import*asOfrom'fp-ts/Option'import{pipe}from'fp-ts/function'constf=(a:string)=>(b:number)=>(c:boolean)=>a+String(b)+String(c)constfa:O.Option<string>=O.some('s')constfb:O.Option<number>=O.some(1)constfc:O.Option<boolean>=O.some(true)assert.deepStrictEqual(pipe(// lift a functionO.some(f),// apply the first argumentO.ap(fa),// apply the second argumentO.ap(fb),// apply the third argumentO.ap(fc)),O.some('s1true'))
Tuple sequencing, i.e., take a tuple of monadic actions and does them from left-to-right, returning the resulting tuple. 元组排序,即采用一元操作的元组并从左到右执行它们,返回结果元组。
Given an element of the base type, of builds an Array containing just that element of the base type (this is useful for building a Monad). 给定一个基本类型的元素, of 构建一个仅包含该基本类型元素的 Array (这对于构建 Monad 很有用)。
Create an array from an Either. The resulting array will contain the content of the Either if it is Right and it will be empty if the Either is Left. 从 Either 创建一个数组。如果 Right 则结果数组将包含 Either 的内容,如果 Either 是 Left 则结果数组将为空。
Create an array from an Option. The resulting array will contain the content of the Option if it is Some and it will be empty if the Option is None. 从 Option 创建一个数组。如果 Some 则结果数组将包含 Option 的内容,如果 Option 是 None 则结果数组将为空。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
In case of Array concatenates the inputs into a single array. 如果是 Array ,则将输入连接到单个数组中。
Compact an array of Options discarding the None values and keeping the Some values. It returns a new array containing the values of the Some options. 压缩 Option 数组,丢弃 None 值并保留 Some 值。它返回一个包含 Some 选项值的新数组。
Given an iterating function that is a Predicate or a Refinement, filter creates a new Array containing the elements of the original Array for which the iterating function is true. 给定一个迭代函数 Predicate 或 Refinement , filter 创建一个新的 Array ,其中包含原始 Array 的元素,而迭代函数为 true 。
Maps an array with an iterating function that returns an Option and it keeps only the Some values discarding the Nones. 使用返回 Option 的迭代函数映射数组,并且仅保留 Some 值并丢弃 None 。
Maps an array with an iterating function that takes the index and the value of each element and returns an Option. It keeps only the Some values discarding the Nones. 使用迭代函数映射数组,该迭代函数获取每个元素的索引和值并返回 Option 。它仅保留 Some 值,丢弃 None 值。
Same as filterMap, but with an iterating function which takes also the index as input. 与 filterMap 相同,但具有迭代函数,该函数也将索引作为输入。
Given an iterating function that is a Predicate or a Refinement, partition creates two new Arrays: right containing the elements of the original Array for which the iterating function is true, left containing the elements for which it is false. 给定一个迭代函数 Predicate 或 Refinement , partition 创建两个新的 Array : right 包含原始 Array 的元素,而迭代函数为 true 、@ 7# 包含为 false 的元素。
Given an iterating function that returns an Either, partitionMap applies the iterating function to each element and it creates two Arrays: right containing the values of Right results, left containing the values of Left results. 给定一个返回 Either 的迭代函数, partitionMap 将迭代函数应用于每个元素,并创建两个 Array : right 包含 Right 结果的值, left 包含 @ 的值6# 结果。
Separate an array of Eithers into Lefts and Rights, creating two new arrays: one containing all the left values and one containing all the right values. 将 Either 数组分成 Left 和 Right ,创建两个新数组:一个包含所有左侧值,另一个包含所有右侧值。
Map and fold an Array. Map the Array passing each value to the iterating function. Then fold the results using the provided Monoid. 映射并折叠 Array 。映射 Array 将每个值传递给迭代函数。然后使用提供的 Monoid 折叠结果。
reduce executes the supplied iterating function on each element of the array, in order, passing in the element and the return value from the calculation on the preceding element. reduce 按顺序对数组的每个元素执行提供的迭代函数,并传入该元素和前一个元素计算的返回值。
The first time that the iterating function is called there is no “return value of the previous calculation”, the initial value is used in its place. 第一次调用迭代函数时,没有“上次计算的返回值”,而是使用初始值。
Get a Magma for Array where the concat function is the differnce between the first and the second array, i.e. the result contains all the elements of the first array for which their is no equal element in the second array according to the Eq provided. 为 Array 获取 Magma ,其中 concat 函数是第一个数组和第二个数组之间的差异,即结果包含第一个数组的所有元素,而它们在第二个数组中的元素不相等,根据提供的 Eq 。
Derives an Eq over the Array of a given element type from the Eq of that type. The derived Eq defines two arrays as equal if all elements of both arrays are compared equal pairwise with the given E. In case of arrays of different lengths, the result is non equality. 从给定元素类型的 Eq 派生出 Eq ,而不是该类型的 Array 。如果两个数组的所有元素与给定的 E 成对比较,则派生的 Eq 将两个数组定义为相等。如果数组长度不同,结果不相等。
Get a Semigroup based on the intersection of the elements of Arrays. Only elements present in the two arrays which are equal according to the provided Eq are included in the result. 根据 Array s 的元素的交集得到 Semigroup 。结果中仅包含根据提供的 Eq 相等的两个数组中存在的元素。
Derives an Ord over the Array of a given element type from the Ord of that type. The ordering between two such arrays is equal to: the first non equal comparison of each arrays elements taken pairwise in increasing order, in case of equality over all the pairwise elements; the longest array is considered the greatest, if both arrays have the same length, the result is equality. 从给定元素类型的 Ord 派生出 Ord ,而不是该类型的 Array 。两个这样的数组之间的顺序等于:如果所有成对元素相等,则按升序对每个数组元素进行第一个不相等比较;最长的数组被认为是最大的,如果两个数组的长度相同,则结果相等。
Get a Monoid based on the union of the elements of Arrays. Elements which equal according to the provided Eq are included only once in the result. 根据 Array s 的元素并集得到 Monoid 。根据提供的 Eq 相等的元素仅在结果中包含一次。
Get a Semigroup based on the union of the elements of Arrays. Elements which equal according to the provided Eq are included only once in the result. See also getUnionMonoid. 根据 Array s 的元素并集得到 Semigroup 。根据提供的 Eq 相等的元素仅在结果中包含一次。另请参阅 getUnionMonoid 。
Given an input an Array of functions, flap returns an Array containing the results of applying each function to the given input. 给定一个输入 Array 函数, flap 返回一个 Array ,其中包含将每个函数应用于给定输入的结果。
map can be used to turn functions (a: A) => B into functions (fa: Array<A>) => Array<B>. In practice it applies the base function to each element of the array and collects the results in a new array. map 可用于将函数 (a: A) => B 转换为函数 (fa: Array<A>) => Array<B> 。实际上,它将基函数应用于数组的每个元素,并将结果收集到一个新数组中。
Takes an array, if the array is empty it returns the result of onEmpty, otherwise it passes the array to onNonEmpty and returns the result. 接受一个数组,如果数组为空则返回 onEmpty 的结果,否则将数组传递给 onNonEmpty 并返回结果。
Takes an array, if the array is empty it returns the result of onEmpty, otherwise it passes the array to onNonEmpty broken into its first element and remaining elements. 接受一个数组,如果数组为空,则返回 onEmpty 的结果,否则将数组传递给 onNonEmpty ,分解为第一个元素和其余元素。
Less strict version of matchLeft. It will work when onEmpty and onNonEmpty have different return types. matchLeft 的不太严格版本。当 onEmpty 和 onNonEmpty 具有不同的返回类型时它将起作用。
import{matchLeftW}from'fp-ts/Array'constf=matchLeftW(()=>0,(head:string,tail:string[])=>`Found "${head}" followed by ${tail.length} elements`)assert.strictEqual(f(['a','b','c']),'Found "a" followed by 2 elements')assert.strictEqual(f([]),0)
Added in v2.11.0 v2.11.0 中添加
matchRight 右匹配
Takes an array, if the array is empty it returns the result of onEmpty, otherwise it passes the array to onNonEmpty broken into its initial elements and the last element. 接受一个数组,如果数组为空,则返回 onEmpty 的结果,否则将数组传递给 onNonEmpty ,分解为初始元素和最后一个元素。
Less strict version of matchRight. It will work when onEmpty and onNonEmpty have different return types. matchRight 的不太严格版本。当 onEmpty 和 onNonEmpty 具有不同的返回类型时它将起作用。
import{matchRightW}from'fp-ts/Array'constf=matchRightW(()=>0,(head:string[],tail:string)=>`Found ${head.length} elements folllowed by "${tail}"`)assert.strictEqual(f(['a','b','c']),'Found 2 elements folllowed by "c"')assert.strictEqual(f([]),0)
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation. 按顺序组成计算,使用一次计算的返回值来确定下一次计算。
In other words it takes a function f that produces an array from a single element of the base type A and returns a new function which applies f to each element of the input array (like map) and, instead of returning an array of arrays, concatenates the results into a single array (like flatten). 换句话说,它采用一个函数 f ,该函数从基本类型 A 的单个元素生成一个数组,并返回一个新函数,该函数将 f 应用于输入数组的每个元素(如 map ),并且,不是返回数组的数组,而是将结果连接到单个数组中(如 flatten )。
Takes an array of arrays of A and flattens them into an array of A by concatenating the elements of each array in order. 获取 A 数组的数组,并通过按顺序连接每个数组的元素将它们展平为 A 数组。
import{traverseWithIndex}from'fp-ts/Array'import{Applicative,left,right}from'fp-ts/lib/Either'constf=(index:number,x:unknown)=>typeofx==='string'?right(x.toUpperCase()+index):left(newError('not a string'))assert.deepStrictEqual(traverseWithIndex(Applicative)(f)(['a','b']),right(['A0','B1']))assert.deepStrictEqual(traverseWithIndex(Applicative)(f)(['a',5]),left(newError('not a string')))
Added in v2.6.3 v2.6.3 中添加
traversing 穿越
sequence 顺序
sequence takes an Array where elements are HKT<A> (higher kinded type) and, using an applicative of that HKT, returns an HKT of Array<A>. E.g. it can turn an Array<Either<Error, string>> into an Either<Error, Array<string>>. sequence 采用 Array ,其中元素为 HKT<A> (高级类型),并使用 HKT 的应用,返回 Array<A> 的 HKT 。例如。它可以将 Array<Either<Error, string>> 变成 Either<Error, Array<string>> 。
sequence requires an Applicative of the HKT you are targeting, e.g. to turn an Array<Either<E, A>> into an Either<E, Array<A>>, it needs an Applicative for Either, to to turn an Array<Option<A>> into an Option<Array<A>>, it needs an Applicative for Option. sequence 需要您所定位的 HKT 的 Applicative ,例如将 Array<Either<E, A>> 变成 Either<E, Array<A>> , Either 需要 Applicative ,将 Array<Option<A>> 变成 Option<Array<A>> , Option 需要 Applicative 。
Signature 签名
exportdeclareconstsequence:Sequence1<'Array'>
Example 例子
import{sequence}from'fp-ts/Array'import{Applicative,left,right}from'fp-ts/lib/Either'assert.deepStrictEqual(sequence(Applicative)([right('a'),right('b')]),right(['a','b']))assert.deepStrictEqual(sequence(Applicative)([right('a'),left(newError('not a string'))]),left(newError('not a string')))
Added in v2.6.3 v2.6.3 中添加
traverse 遍历
Given an iterating function that returns a HKT (higher kinded type), traverse applies the iterating function to each element of the Array and then sequence-s the results using the provided Applicative. 给定一个返回 HKT (更高种类类型)的迭代函数, traverse 将迭代函数应用于 Array 的每个元素,然后使用提供的 Applicativesequence -s 结果。
E.g. suppose you have an Array and you want to format each element with a function that returns a result or an error as f = (a: A) => Either<Error, B>, using traverse you can apply f to all elements and directly obtain as a result an Either<Error,Array<B>> i.e. an Array<B> if all the results are B, or an Error if some of the results are Errors. 例如。假设您有一个 Array 并且您想要使用返回结果或错误的函数格式化每个元素作为 f = (a: A) => Either<Error, B> ,使用 traverse 您可以将 f 应用于所有元素并直接获得 @ 作为结果4#,即如果所有结果都是 B ,则为 Array<B> ;如果某些结果是 Error ,则为 Error 。
import{traverse}from'fp-ts/Array'import{Applicative,left,right}from'fp-ts/lib/Either'constf=(x:unknown)=>(typeofx==='string'?right(x.toUpperCase()):left(newError('not a string')))assert.deepStrictEqual(traverse(Applicative)(f)(['a','b']),right(['A','B']))assert.deepStrictEqual(traverse(Applicative)(f)(['a',5]),left(newError('not a string')))
import{ap,map,of}from'fp-ts/Array'import{pipe}from'fp-ts/function'// a curried function with 3 input parameteresconstf=(s1:string)=>(n:number)=>(s2:string)=>s1+n+s2// let's use `ap` to iterate `f` over an array for each input parameterassert.deepStrictEqual(pipe(['a','b'],map(f),ap([1,2]),ap(['😀','😫','😎'])),['a1😀','a1😫','a1😎','a2😀','a2😫','a2😎','b1😀','b1😫','b1😎','b2😀','b2😫','b2😎',])// given Array implements the Applicative interface with the `of` method,// we can write exactly the same thing in a more symmetric way// using `of` on `f` and `ap` on each array in inputassert.deepStrictEqual(pipe(of(f),ap(['a','b']),ap([1,2]),ap(['😀','😫','😎'])),pipe(['a','b'],map(f),ap([1,2]),ap(['😀','😫','😎'])))
Added in v2.0.0 v2.0.0 中添加
apFirst 应用程序第一
Combine two effectful actions, keeping only the result of the first. 结合两个有效的操作,仅保留第一个操作的结果。
A useful recursion pattern for processing an array to produce a new array, often used for “chopping” up the input array. Typically chop is called with some function that will consume an initial prefix of the array and produce a value and the rest of the array. 一种有用的递归模式,用于处理数组以生成新数组,通常用于“切碎”输入数组。通常,chop 是通过某个函数调用的,该函数将消耗数组的初始前缀并生成一个值和数组的其余部分。
Splits an array into length-n pieces. The last piece will be shorter if n does not evenly divide the length of the array. Note that chunksOf(n)([]) is [], not [[]]. This is intentional, and is consistent with a recursive definition of chunksOf; it satisfies the property that 将数组分割成长度为 n 的片段。如果 n 没有均匀划分数组的长度,那么最后一段会更短。请注意, chunksOf(n)([]) 是 [] ,而不是 [[]] 。这是故意的,并且与 chunksOf 的递归定义一致;它满足以下性质
This function takes an array and makes a new array containing the same elements. 该函数接受一个数组并创建一个包含相同元素的新数组。
Signature 签名
exportdeclareconstcopy:<A>(as:A[])=>A[]
Added in v2.0.0 v2.0.0 中添加
deleteAt 删除处
Delete the element at the specified index, creating a new array, or returning None if the index is out of bounds. 删除指定索引处的元素,创建一个新数组,或者如果索引越界则返回 None 。
Creates an array of array values not included in the other given array using a Eq for equality comparisons. The order and references of result values are determined by the first array. 使用 Eq 创建不包含在其他给定数组中的数组值进行相等比较。结果值的顺序和引用由第一个数组确定。
Creates a new Array which is a copy of the input dropping the longest initial subarray for which all element satisfy the specified predicate. 创建一个新的 Array ,它是输入的副本,删除所有元素都满足指定谓词的最长初始子数组。
duplicate returns an array containing the whole input Array, then to the input Array dropping the first element, then to the input Array dropping the first two elements, etc. duplicate 返回一个包含整个输入 Array 的数组,然后返回到输入 Array 删除第一个元素,然后返回到输入 Array 删除前两个元素,依此类推。
Test if a value is a member of an Array. Takes a Eq<A> as a single argument which returns the function to use to search for a value of type A in an Array<A>. 测试某个值是否是 Array 的成员。将 Eq<A> 作为单个参数,返回用于在 Array<A> 中搜索 A 类型的值的函数。
Given an iterating function that takes Array<A> as input, extend returns an array containing the results of the iterating function applied to the whole input Array, then to the input Array without the first element, then to the input Array without the first two elements, etc. 给定一个以 Array<A> 作为输入的迭代函数, extend 返回一个数组,其中包含迭代函数的结果,该迭代函数应用于整个输入 Array ,然后应用于没有第一个元素的输入 Array ,然后应用于输入 Array 没有前两个元素,等等。
Find the first element which satisfies a predicate (or a refinement) function. It returns an Option containing the element or None if not found. 查找满足谓词(或细化)函数的第一个元素。它返回包含该元素的 Option ,如果未找到则返回 None 。
Given a selector function which takes an element and returns an option, this function applies the selector to each element of the array and returns the first Some result. Otherwise it returns None. 给定一个接受一个元素并返回一个选项的选择器函数,该函数将选择器应用于数组的每个元素并返回第一个 Some 结果。否则返回 None 。
findIndex returns an Option containing the first index for which a predicate holds. It returns None if no element satisfies the predicate. Similar to findFirst but returning the index instead of the element. findIndex 返回一个 Option ,其中包含谓词所保留的第一个索引。如果没有元素满足谓词,则返回 None 。与 findFirst 类似,但返回索引而不是元素。
Find the last element which satisfies a predicate function. It returns an Option containing the element or None if not found. 找到满足谓词函数的最后一个元素。它返回包含该元素的 Option ,如果未找到则返回 None 。
Returns the index of the last element of the list which matches the predicate. It returns an Option containing the index or None if not found. 返回列表中与谓词匹配的最后一个元素的索引。它返回包含索引的 Option ,如果未找到则返回 None 。
Given a selector function which takes an element and returns an option, this function applies the selector to each element of the array starting from the end and returns the last Some result. Otherwise it returns None. 给定一个接受一个元素并返回一个选项的选择器函数,该函数将选择器从末尾开始应用于数组的每个元素,并返回最后一个 Some 结果。否则返回 None 。
Insert an element at the specified index, creating a new array, or returning None if the index is out of bounds. 在指定索引处插入一个元素,创建一个新数组,或者如果索引越界则返回 None 。
Creates an array of unique values that are included in all given arrays using a Eq for equality comparisons. The order and references of result values are determined by the first array. 创建一个包含在所有给定数组中的唯一值数组,使用 Eq 进行相等比较。结果值的顺序和引用由第一个数组确定。
Takes an Array of Either and produces a new Array containing the values of all the Left elements in the same order. 获取 Either 的 Array 并生成一个新的 Array ,其中包含按相同顺序排列的所有 Left 元素的值。
This function provides a safe way to read a value at a particular index from an array. It returns a none if the index is out of bounds, and a some of the element if the index is valid. 此函数提供了一种从数组中读取特定索引处的值的安全方法。如果索引越界,则返回 none ;如果索引有效,则返回元素的 some 。
Apply a function to the element at the specified index, creating a new array, or returning None if the index is out of bounds. 将函数应用于指定索引处的元素,创建一个新数组,或者如果索引越界则返回 None 。
Takes an Array of Either and produces a new Array containing the values of all the Right elements in the same order. 获取 Either 的 Array 并生成一个新的 Array ,其中包含按相同顺序排列的所有 Right 元素的值。
Sort the elements of an array in increasing order, where elements are compared using first ords[0], then ords[1], etc… 按升序对数组的元素进行排序,其中首先使用 ords[0] ,然后使用 ords[1] 等比较元素......
unfold takes a function f which returns an Option of a tuple containing an outcome value and an input for the following iteration. unfold applies f to the initial value b and then recursively to the second element of the tuple contained in the returned option of the previous calculation until f returns Option.none. unfold 接受一个函数 f ,该函数返回一个元组的 Option ,其中包含后续迭代的结果值和输入。 unfold 将 f 应用到初始值 b ,然后递归到先前计算返回的 option 中包含的元组的第二个元素,直到 f 返回 Option.none 。
Creates a new Array removing duplicate elements, keeping the first occurrence of an element, based on a Eq<A>. 基于 Eq<A> 创建一个新的 Array ,删除重复元素,保留元素的第一次出现。
Makes an empty Array, useful for building a Monoid 制作一个空的 Array ,对于构建 Monoid 很有用
Signature 签名
exportdeclareconstzero:<A>()=>A[]
Added in v2.7.0 v2.7.0 中添加
zip 压缩
Takes two arrays and returns an array of corresponding pairs. If one input array is short, excess elements of the longer array are discarded 接受两个数组并返回对应对的数组。如果一个输入数组很短,则较长数组中多余的元素将被丢弃
Apply a function to pairs of elements at the same index in two arrays, collecting the results in a new array. If one input array is short, excess elements of the longer array are discarded. 将函数应用于两个数组中相同索引处的元素对,并将结果收集到新数组中。如果一个输入数组很短,则较长数组中多余的元素将被丢弃。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass A.Functor instead of A.array (where A is from import A from 'fp-ts/Array') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 A.Functor 而不是 A.array (其中 A 来自 import A from 'fp-ts/Array' )
Defines the fold over a boolean value. Takes two thunks onTrue, onFalse and a boolean value. If value is false, onFalse() is returned, otherwise onTrue(). 定义布尔值的折叠。采用两个 thunk onTrue 、 onFalse 和一个 boolean 值。如果 value 为假,则返回 onFalse() ,否则返回 onTrue() 。
Boolean algebras are Heyting algebras with the additional constraint that the law of the excluded middle is true (equivalently, double-negation is true). 布尔代数是带有额外约束的 Heyting 代数,即排中律为真(等效地,双重否定为真)。
Instances should satisfy the following laws in addition to the HeytingAlgebra laws: 除了 HeytingAlgebra 定律外,实例还应满足以下定律:
Excluded middle: a ∨ ¬a <-> 1 排除中间: a ∨ ¬a <-> 1
Boolean algebras generalize classical logic: one is equivalent to “true” and zero is equivalent to “false”. 布尔代数概括了经典逻辑:1 相当于“真”,0 相当于“假”。
A BoundedJoinSemilattice must satisfy the following laws in addition to JoinSemilattice laws: 除了 JoinSemilattice 法则之外, BoundedJoinSemilattice 还必须满足以下法则:
A BoundedLattice must satisfy the following in addition to BoundedMeetSemilattice and BoundedJoinSemilattice laws: 除了 BoundedMeetSemilattice 和 BoundedJoinSemilattice 定律之外, BoundedLattice 还必须满足以下条件:
Absorption law for meet: a ∧ (a ∨ b) <-> a 满足吸收定律: a ∧ (a ∨ b) <-> a
Absorption law for join: a ∨ (a ∧ b) <-> a join 的吸收定律: a ∨ (a ∧ b) <-> a
A BoundedMeetSemilattice must satisfy the following laws in addition to MeetSemilattice laws: 除了 MeetSemilattice 法则之外, BoundedMeetSemilattice 还必须满足以下法则:
The Chain type class extends the Apply type class with a chain operation which composes computations in sequence, using the return value of one computation to determine the next computation. Chain 类型类使用 chain 操作扩展了 Apply 类型类,chain 操作按顺序组成计算,使用一个计算的返回值来确定下一个计算。
Instances must satisfy the following law in addition to the Apply laws: 除了 Apply 法则之外,实例还必须满足以下法则:
Associativity: F.chain(F.chain(fa, afb), bfc) <-> F.chain(fa, a => F.chain(afb(a), bfc)) 关联性: F.chain(F.chain(fa, afb), bfc) <-> F.chain(fa, a => F.chain(afb(a), bfc))
Note. Apply’s ap can be derived: (fab, fa) => F.chain(fab, f => F.map(fa, f)) 笔记。 Apply 的@1#可以推导出: (fab, fa) => F.chain(fab, f => F.map(fa, f))
The Choice class extends Profunctor with combinators for working with sum types. Choice 类使用组合器扩展了 Profunctor ,以处理求和类型。
left and right lift values in a Profunctor to act on the Left and Right components of a sum, respectively. left 和 right 提升 Profunctor 中的值,分别作用于总和的 Left 和 Right 部分。
Looking at Choice through the intuition of inputs and outputs yields the following type signature: 通过输入和输出的直觉查看 Choice 会产生以下类型签名:
left :: forall input output a. p input output -> p (Either input a) (Either output a)
right :: forall input output a. p input output -> p (Either a input) (Either a output)
If we specialize the profunctor p to the function arrow, we get the following type signatures: 如果我们将表示符 p 专门化为 function 箭头,我们会得到以下类型签名:
left :: forall input output a. (input -> output) -> (Either input a) -> (Either output a)
right :: forall input output a. (input -> output) -> (Either a input) -> (Either a output)
When the profunctor is Function application, left allows you to map a function over the left side of an Either, and right maps it over the right side (same as map would do). 当 profunctor 是 Function 应用程序时, left 允许您将函数映射到 Either 的左侧, right 将其映射到右侧(与 map 相同)。
Adapted from https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Choice.purs 改编自https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Choice.purs
Compose a value which eliminates a sum from two values, each eliminating one side of the sum. 组成一个值,从两个值中减去总和,每个值都消除总和的一侧。
This combinator is useful when assembling values from smaller components, because it provides a way to support two different types of input. 当从较小的组件组装值时,此组合器非常有用,因为它提供了一种支持两种不同类型输入的方法。
Specializing fanIn to function application would look like this: 将 fanIn 专门化为函数应用程序将如下所示:
fanIn :: forall a b c d. (a -> c) -> (b -> c) -> Either a b -> c
We take two functions, f and g, which both return the same type c and we transform them into a single function which takes an Either value with the parameter type of f on the left side and the parameter type of g on the right side. The function then runs either f or g, depending on whether the Either value is a Left or a Right. This allows us to bundle two different computations which both have the same result type into one function which will run the appropriate computation based on the parameter supplied in the Either value. 我们采用两个函数 f 和 g ,它们都返回相同类型的 c ,我们将它们转换为单个函数,该函数采用 Either 值,左侧参数类型为 f ,右侧 g 的参数类型。然后,该函数运行 f 或 g ,具体取决于 Either 值是 Left 还是 Right 。这允许我们将两个具有相同结果类型的不同计算捆绑到一个函数中,该函数将根据 Either 值中提供的参数运行适当的计算。
Compose a value acting on a sum from two values, each acting on one of the components of the sum. 由两个值组成一个作用于总和的值,每个值作用于总和的一个分量。
Specializing split to function application would look like this: 将 split 专门化为函数应用程序将如下所示:
split :: forall a b c d. (a -> b) -> (c -> d) -> (Either a c) -> (Either b d)
We take two functions, f and g, and we transform them into a single function which takes an Eitherand maps f over the left side and g over the right side. Just like bimap would do for the Bifunctor instance of Either. 我们采用两个函数 f 和 g ,并将它们转换为一个函数,该函数采用 Either 并将 f 映射到左侧,将 g 映射到右侧。就像 bimap 对 Either 的 Bifunctor 实例所做的那样。
Compactable represents data structures which can be compacted/filtered. This is a generalization of catOptions as a new function compact. compact has relations with Functor, Applicative, Monad, Alternative, and Traversable in that we can use these classes to provide the ability to operate on a data type by eliminating intermediate Nones. This is useful for representing the filtering out of values, or failure. Compactable 表示可以压缩/过滤的数据结构。这是 catOptions 作为新函数 compact 的概括。 compact 与 Functor 、 Applicative 、 Monad 、 Alternative 和 Traversable 有关系,因为我们可以使用这些类通过消除中间的 None 来提供对数据类型进行操作的能力。这对于表示过滤掉值或失败非常有用。
Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Compactable.purs 改编自https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Compactable.purs
exportinterfaceCompactable<F>{readonlyURI:F/**
* Compacts a data structure unwrapping inner Option
*/readonlycompact:<A>(fa:HKT<F,Option<A>>)=>HKT<F,A>/**
* Separates a data structure moving inner Left to the left side and inner Right to the right side of Separated
*/readonlyseparate:<A,B>(fa:HKT<F,Either<A,B>>)=>S.Separated<HKT<F,A>,HKT<F,B>>}
The Const type constructor, which wraps its first type argument and ignores its second. That is, Const<E, A> is isomorphic to E for any A. Const 类型构造函数,包装其第一个类型参数并忽略第二个类型参数。也就是说,对于任何 A , Const<E, A> 与 E 同构。
Const has some useful instances. For example, the Applicative instance allows us to collect results using a Monoid while ignoring return values. Const 有一些有用的实例。例如, Applicative 实例允许我们使用 Monoid 收集结果,同时忽略返回值。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass C.Functor instead of C.const_ (where C is from import C from 'fp-ts/Const') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 C.Functor 而不是 C.const_ (其中 C 来自 import C from 'fp-ts/Const' )
Represents a value of one of two possible types (a disjoint union). 表示两种可能类型之一的值(不相交并集)。
An instance of Either is either an instance of Left or Right. Either 的实例是 Left 或 Right 的实例。
A common use of Either is as an alternative to Option for dealing with possible missing values. In this usage, None is replaced with a Left which can contain useful information. Right takes the place of Some. Convention dictates that Left is used for failure and Right is used for success. Either 的常见用途是作为 Option 的替代方案来处理可能的缺失值。在此用法中, None 替换为可以包含有用信息的 Left 。 Right 取代 Some 。按照约定, Left 用于表示失败, Right 用于表示成功。
Example 例子
import*asEfrom'fp-ts/Either'import{pipe}from'fp-ts/function'constdouble=(n:number):number=>n*2exportconstimperative=(as:ReadonlyArray<number>):string=>{consthead=(as:ReadonlyArray<number>):number=>{if(as.length===0){thrownewError('empty array')}returnas[0]}constinverse=(n:number):number=>{if(n===0){thrownewError('cannot divide by zero')}return1/n}try{return`Result is ${inverse(double(head(as)))}`}catch(err:any){return`Error is ${err.message}`}}exportconstfunctional=(as:ReadonlyArray<number>):string=>{consthead=<A>(as:ReadonlyArray<A>):E.Either<string,A>=>as.length===0?E.left('empty array'):E.right(as[0])constinverse=(n:number):E.Either<string,number>=>(n===0?E.left('cannot divide by zero'):E.right(1/n))returnpipe(as,head,E.map(double),E.flatMap(inverse),E.match((err)=>`Error is ${err}`,// onLeft handler(head)=>`Result is ${head}`// onRight handler))}assert.deepStrictEqual(imperative([1,2,3]),functional([1,2,3]))assert.deepStrictEqual(imperative([]),functional([]))assert.deepStrictEqual(imperative([0]),functional([0]))
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Constructs a new Either holding a Left value. This usually represents a failure, due to the right-bias of this structure. 构造一个新的 Either ,保存 Left 值。由于该结构的右偏,这通常代表失败。
Constructs a new Either holding a Right value. This usually represents a successful value due to the right bias of this structure. 构造一个新的 Either ,保存 Right 值。由于该结构的正确偏差,这通常代表成功的值。
Takes a default and a nullable value, if the value is not nully, turn it into a Right, if the value is nully use the provided default as a Left. 接受一个默认值和一个可为空的值,如果该值不为空,则将其转换为 Right ,如果该值为空,则使用提供的默认值作为 Left 。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
In case of Either returns the left-most non-Left value (or the right-most Left value if both values are Left). 如果是 Either ,则返回最左边的非 Left 值(如果两个值都是 Left ,则返回最右边的 Left 值)。
The default Alt instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 Alt 实例返回最后一个错误,如果你想获取所有错误,你需要提供一种通过 Semigroup 连接它们的方法。
import*asEfrom'fp-ts/Either'import{pipe}from'fp-ts/function'import*asSfrom'fp-ts/Semigroup'import*asstringfrom'fp-ts/string'constparseString=(u:unknown):E.Either<string,string>=>typeofu==='string'?E.right(u):E.left('not a string')constparseNumber=(u:unknown):E.Either<string,number>=>typeofu==='number'?E.right(u):E.left('not a number')constparse=(u:unknown):E.Either<string,string|number>=>pipe(parseString(u),E.alt<string,string|number>(()=>parseNumber(u)))assert.deepStrictEqual(parse(true),E.left('not a number'))// <= last errorconstAlt=E.getAltValidation(pipe(string.Semigroup,S.intercalate(', ')))constparseAll=(u:unknown):E.Either<string,string|number>=>Alt.alt<string|number>(parseString(u),()=>parseNumber(u))assert.deepStrictEqual(parseAll(true),E.left('not a string, not a number'))// <= all errors
Added in v2.7.0 v2.7.0 中添加
getApplicativeValidation 获取应用验证
The default Applicative instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 Applicative 实例返回第一个错误,如果您想获取所有错误,您需要提供一种通过 Semigroup 连接它们的方法。
import*asAfrom'fp-ts/Apply'import*asEfrom'fp-ts/Either'import{pipe}from'fp-ts/function'import*asSfrom'fp-ts/Semigroup'import*asstringfrom'fp-ts/string'constparseString=(u:unknown):E.Either<string,string>=>typeofu==='string'?E.right(u):E.left('not a string')constparseNumber=(u:unknown):E.Either<string,number>=>typeofu==='number'?E.right(u):E.left('not a number')interfacePerson{readonlyname:stringreadonlyage:number}constparsePerson=(input:Record<string,unknown>):E.Either<string,Person>=>pipe(E.Do,E.apS('name',parseString(input.name)),E.apS('age',parseNumber(input.age)))assert.deepStrictEqual(parsePerson({}),E.left('not a string'))// <= first errorconstApplicative=E.getApplicativeValidation(pipe(string.Semigroup,S.intercalate(', ')))constapS=A.apS(Applicative)constparsePersonAll=(input:Record<string,unknown>):E.Either<string,Person>=>pipe(E.Do,apS('name',parseString(input.name)),apS('age',parseNumber(input.age)))assert.deepStrictEqual(parsePersonAll({}),E.left('not a string, not a number'))// <= all errors
Added in v2.7.0 v2.7.0 中添加
getOrElse 获取或否则
Returns the wrapped value if it’s a Right or a default value if is a Left. 如果是 Right ,则返回包装值;如果是 Left ,则返回默认值。
Semigroup returning the left-most non-Left value. If both operands are Rights then the inner values are concatenated using the provided Semigroup 半群返回最左边的非 Left 值。如果两个操作数都是 Right s,则使用提供的 Semigroup 连接内部值
Takes two functions and an Either value, if the value is a Left the inner value is applied to the first function, if the value is a Right the inner value is applied to the second function. 接受两个函数和一个 Either 值,如果该值为 Left ,则内部值应用于第一个函数,如果该值为 Right ,则内部值应用于第二个函数。
The flatten function is the conventional monad join operator. It is used to remove one level of monadic structure, projecting its bound argument into the outer level. flatten 函数是传统的 monad 连接运算符。它用于删除一层单子结构,将其绑定参数投射到外层。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass E.Functor instead of E.either (where E is from import E from 'fp-ts/Either') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 E.Functor 而不是 E.either (其中 E 来自 import E from 'fp-ts/Either' )
Semigroup returning the left-most Left value. If both operands are Rights then the inner values are concatenated using the provided Semigroup 半群返回最左边的 Left 值。如果两个操作数都是 Right s,则使用提供的 Semigroup 连接内部值
The error monad transformer. It can be used to add error handling to other monads. 错误单子转换器。它可用于向其他 monad 添加错误处理。
The of function yields a successful computation, while chain sequences two subcomputations, failing on the first error. of 函数产生成功的计算,而 chain 对两个子计算进行排序,因第一个错误而失败。
The Eq type class represents types which support decidable equality. Eq 类型类表示支持可判定相等的类型。
Instances must satisfy the following laws: 实例必须满足以下定律:
Reflexivity: E.equals(a, a) === true 自反性: E.equals(a, a) === true
Symmetry: E.equals(a, b) === E.equals(b, a) 对称性: E.equals(a, b) === E.equals(b, a)
Transitivity: if E.equals(a, b) === true and E.equals(b, c) === true, then E.equals(a, c) === true 传递性:如果 E.equals(a, b) === true 和 E.equals(b, c) === true ,则 E.equals(a, c) === true
A typical use case for contramap would be like, given some User type, to construct an Eq<User>. contramap 的典型用例类似于,给定一些 User 类型,构造一个 Eq<User> 。
We can do so with a function from User -> X where X is some value that we know how to compare for equality (meaning we have an Eq<X>) 我们可以使用 User -> X 中的函数来做到这一点,其中 X 是我们知道如何比较相等性的某个值(意味着我们有一个 Eq<X> )
For example, given the following User type, we want to construct an Eq<User> that just looks at the key field for each user (since it’s known to be unique). 例如,给定以下 User 类型,我们想要构造一个 Eq<User> ,它只查看每个用户的 key 字段(因为已知它是唯一的)。
If we have a way of comparing UUIDs for equality (eqUUID: Eq<UUID>) and we know how to go from User -> UUID, using contramap we can do this 如果我们有办法比较 UUID s是否相等( eqUUID: Eq<UUID> )并且我们知道如何从 User -> UUID 开始,使用 contramap 我们可以做到这一点
This instance is deprecated, use small, specific instances instead. For example if a function needs a Contravariant instance, pass E.Contravariant instead of E.eq (where E is from import E from 'fp-ts/Eq') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Contravariant 实例,请传递 E.Contravariant 而不是 E.eq (其中 E 来自 import E from 'fp-ts/Eq' )
Adapted from https://github.com/purescript/purescript-prelude/blob/master/src/Data/Field.purs 改编自https://github.com/purescript/purescript-prelude/blob/master/src/Data/Field.purs
Filterable represents data structures which can be partitioned/filtered. Filterable 表示可以分区/过滤的数据结构。
Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Filterable.purs 改编自https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Filterable.purs
exportinterfaceFilterable<F>extendsFunctor<F>,Compactable<F>{/**
* Partition a data structure based on an either predicate.
*/readonlypartitionMap:<A,B,C>(fa:HKT<F,A>,f:(a:A)=>Either<B,C>)=>Separated<HKT<F,B>,HKT<F,C>>/**
* Partition a data structure based on a boolean predicate.
*/readonlypartition:Partition<F>/**
* Map over a data structure and filter based on an option predicate.
*/readonlyfilterMap:<A,B>(fa:HKT<F,A>,f:(a:A)=>Option<B>)=>HKT<F,B>/**
* Filter a data structure based on a boolean predicate.
*/readonlyfilter:Filter<F>}
Fold a data structure, accumulating values in some Monoid, combining adjacent elements using the specified separator 折叠一个数据结构,在一些 Monoid 中累加值,使用指定的分隔符组合相邻元素
Traverse a data structure, performing some effects encoded by an Applicative functor at each value, ignoring the final result. 遍历数据结构,对每个值执行由 Applicative 函子编码的一些效果,忽略最终结果。
A Foldable with an additional index. A FoldableWithIndex instance must be compatible with its Foldable instance 带有附加索引的 Foldable 。 FoldableWithIndex 实例必须与其 Foldable 实例兼容
Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary. 执行从左到右的函数组合。第一个参数可以具有任意元数,其余参数必须是一元的。
import{pipe}from'fp-ts/function'constlen=(s:string):number=>s.lengthconstdouble=(n:number):number=>n*2// without pipeassert.strictEqual(double(len('aaa')),6)// with pipeassert.strictEqual(pipe('aaa',len,double),6)
A Functor is a type constructor which supports a mapping operation map. Functor 是支持映射操作 map 的类型构造函数。
map can be used to turn functions a -> b into functions f a -> f b whose argument and return types use the type constructor f to represent some computational context. map 可用于将函数 a -> b 转换为函数 f a -> f b ,其参数和返回类型使用类型构造函数 f 来表示某些计算上下文。
Instances must satisfy the following laws: 实例必须满足以下定律:
Identity: F.map(fa, a => a) <-> fa 身份: F.map(fa, a => a) <-> fa
Composition: F.map(fa, a => bc(ab(a))) <-> F.map(F.map(fa, ab), bc) 成分: F.map(fa, a => bc(ab(a))) <-> F.map(F.map(fa, ab), bc)
A FunctorWithIndex is a type constructor which supports a mapping operation mapWithIndex. FunctorWithIndex 是支持映射操作 mapWithIndex 的类型构造函数。
mapWithIndex can be used to turn functions i -> a -> b into functions f a -> f b whose argument and return types use the type constructor f to represent some computational context. mapWithIndex 可用于将函数 i -> a -> b 转换为函数 f a -> f b ,其参数和返回类型使用类型构造函数 f 来表示某些计算上下文。
Instances must satisfy the following laws: 实例必须满足以下定律:
Identity: F.mapWithIndex(fa, (_i, a) => a) <-> fa 身份: F.mapWithIndex(fa, (_i, a) => a) <-> fa
Composition: F.mapWithIndex(fa, (_i, a) => bc(ab(a))) <-> F.mapWithIndex(F.mapWithIndex(fa, ab), bc) 成分: F.mapWithIndex(fa, (_i, a) => bc(ab(a))) <-> F.mapWithIndex(F.mapWithIndex(fa, ab), bc)
A Group is a Monoid with inverses. Instances must satisfy the following law in addition to the monoid laws: Group 是带有逆元的 Monoid 。除了幺半群法则之外,实例还必须满足以下法则:
Inverse: concat(inverse(a), a) <-> empty = concat(a, inverse(a)) 逆: concat(inverse(a), a) <-> empty = concat(a, inverse(a))
Heyting algebras are bounded (distributive) lattices that are also equipped with an additional binary operation implies (also written as →). Heyting algebras also define a complement operation not (sometimes written as ¬a) Heyting 代数是有界(分配)格,还配备了额外的二元运算 implies (也写为 → )。 Heyting 代数还定义补运算 not (有时写为 ¬a )
However, in Heyting algebras this operation is only a pseudo-complement, since Heyting algebras do not necessarily provide the law of the excluded middle. This means that there is no guarantee that a ∨ ¬a = 1. 然而,在 Heyting 代数中,这种运算只是伪补,因为 Heyting 代数不一定提供排中律。这意味着不能保证 a ∨ ¬a = 1 。
Heyting algebras model intuitionistic logic. For a model of classical logic, see the boolean algebra type class implemented as BooleanAlgebra. 海廷代数模型直观逻辑。对于经典逻辑模型,请参阅实现为 BooleanAlgebra 的布尔代数类型类。
A HeytingAlgebra must satisfy the following laws in addition to BoundedDistributiveLattice laws: 除了 BoundedDistributiveLattice 法则之外, HeytingAlgebra 还必须满足以下法则:
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass I.Functor instead of I.identity (where I is from import I from 'fp-ts/Identity') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 I.Functor 而不是 I.identity (其中 I 来自 import I from 'fp-ts/Identity' )
IO<A> represents a non-deterministic synchronous computation that can cause side effects, yields a value of type A and never fails. IO<A> 表示非确定性同步计算,可能会导致副作用,产生 A 类型的值并且永远不会失败。
If you want to represent a synchronous computation that may fail, please see IOEither. If you want to represent a synchronous computation that may yield nothing, please see IOOption. 如果你想表示一个可能失败的同步计算,请参见 IOEither 。如果您想表示可能不会产生任何结果的同步计算,请参阅 IOOption 。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass IO.Functor instead of IO.io (where IO is from import IO from 'fp-ts/IO') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 IO.Functor 而不是 IO.io (其中 IO 来自 import IO from 'fp-ts/IO' )
IOEither<E, A> represents a synchronous computation that either yields a value of type A or fails yielding an error of type E. IOEither<E, A> 表示同步计算,它要么生成 A 类型的值,要么失败并生成 E 类型的错误。
If you want to represent a synchronous computation that never fails, please see IO. If you want to represent a synchronous computation that may yield nothing, please see IOOption. 如果你想表示永不失败的同步计算,请参阅 IO 。如果您想表示可能不会产生任何结果的同步计算,请参阅 IOOption 。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{pipe}from'fp-ts/function'import*asIOEfrom'fp-ts/IOEither'import*asEfrom'fp-ts/Either'import*asConsolefrom'fp-ts/Console'constsayHello=(value:string)=>Console.log(`Hello, ${value}`)// Will produce `Hello, fp-ts` to the stdoutconsteffectA=IOE.tapIO(IOE.of('fp-ts'),sayHello)// No output to the stdoutconsteffectB=pipe(IOE.left<string>('error'),IOE.tapIO(sayHello))assert.deepStrictEqual(effectA(),E.right('fp-ts'))assert.deepStrictEqual(effectB(),E.left('error'))
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
The default Alt instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 Alt 实例返回最后一个错误,如果你想获取所有错误,你需要提供一种通过 Semigroup 连接它们的方法。
The default ApplicativePar instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 ApplicativePar 实例返回第一个错误,如果您想获取所有错误,您需要提供一种通过 Semigroup 连接它们的方法。
Returns a IOEither whose failure and success channels have been mapped by the specified pair of functions, f and g. 返回一个 IOEither ,其失败和成功通道已由指定的函数对 f 和 g 映射。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Make sure that a resource is cleaned up in the event of an exception (*). The release action is called regardless of whether the body action throws (*) or returns. 确保在发生异常时清理资源 (*)。无论主体操作是抛出 (*) 还是返回,都会调用释放操作。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass IOE.Functor instead of IOE.ioEither (where IOE is from import IOE from 'fp-ts/IOEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 IOE.Functor 而不是 IOE.ioEither (其中 IOE 来自 import IOE from 'fp-ts/IOEither' )
IOOption<A> represents a synchronous computation that either yields a value of type A or nothing. IOOption<A> 表示同步计算,要么产生 A 类型的值,要么不产生任何结果。
If you want to represent a synchronous computation that never fails, please see IO. If you want to represent a synchronous computation that may fail, please see IOEither. 如果你想表示永不失败的同步计算,请参阅 IO 。如果你想表示一个可能失败的同步计算,请参见 IOEither 。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{pipe}from'fp-ts/function'import*asIOOfrom'fp-ts/IOOption'import*asOfrom'fp-ts/Option'import*asConsolefrom'fp-ts/Console'// Will produce `Hello, fp-ts` to the stdoutconsteffectA=pipe(IOO.of('fp-ts'),IOO.tapIO((value)=>Console.log(`Hello, ${value}`)))// No output to the stdoutconsteffectB=pipe(IOO.noneasIOO.IOOption<string>,IOO.tapIO((value)=>Console.log(`Hello, ${value}`)))asyncfunctiontest(){assert.deepStrictEqual(effectA(),O.of('fp-ts'))assert.deepStrictEqual(effectB(),O.none)}test()
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
A join-semilattice (or upper semilattice) is a semilattice whose operation is called join, and which can be thought of as a least upper bound. 连接半格(或上半格)是其操作称为 join 的半格,可以将其视为最小上界。
A JoinSemilattice must satisfy the following laws: JoinSemilattice 必须满足以下定律:
Associativity: a ∨ (b ∨ c) <-> (a ∨ b) ∨ c 关联性: a ∨ (b ∨ c) <-> (a ∨ b) ∨ c
Commutativity: a ∨ b <-> b ∨ a 交换性: a ∨ b <-> b ∨ a
import*asJfrom'fp-ts/Json'import*asEfrom'fp-ts/Either'import{pipe}from'fp-ts/function'assert.deepStrictEqual(pipe('{"a":1}',J.parse),E.right({a:1}))assert.deepStrictEqual(pipe('{"a":}',J.parse),E.left(newSyntaxError('Unexpected token } in JSON at position 5')))
Added in v2.10.0 v2.10.0 中添加
stringify 字符串化
Converts a JavaScript value to a JavaScript Object Notation (JSON) string. 将 JavaScript 值转换为 JavaScript 对象表示法 (JSON) 字符串。
import*asEfrom'fp-ts/Either'import*asJfrom'fp-ts/Json'import{pipe}from'fp-ts/function'assert.deepStrictEqual(J.stringify({a:1}),E.right('{"a":1}'))constcircular:any={ref:null}circular.ref=circularassert.deepStrictEqual(pipe(J.stringify(circular),E.mapLeft((e)=>einstanceofError&&e.message.includes('Converting circular structure to JSON'))),E.left(true))
Added in v2.10.0 v2.10.0 中添加
Lattice overview 格子概述
A Lattice must satisfy the following in addition to JoinSemilattice and MeetSemilattice laws: 除了 JoinSemilattice 和 MeetSemilattice 定律之外, Lattice 还必须满足以下条件:
Absorbtion law for meet: a ∧ (a ∨ b) <-> a 满足吸收定律: a ∧ (a ∨ b) <-> a
Absorbtion law for join: a ∨ (a ∧ b) <-> a 连接吸收定律: a ∨ (a ∧ b) <-> a
Create a map from a foldable collection of key/value pairs, using the specified Magma to combine values for duplicate keys. 从可折叠的键/值对集合创建映射,使用指定的 Magma 来组合重复键的值。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
A meet-semilattice (or lower semilattice) is a semilattice whose operation is called meet, and which can be thought of as a greatest lower bound. 交半格(或下半格)是其操作称为 meet 的半格,可以将其视为最大下界。
A MeetSemilattice must satisfy the following laws: MeetSemilattice 必须满足以下定律:
Associativity: a ∧ (b ∧ c) <-> (a ∧ b) ∧ c 关联性: a ∧ (b ∧ c) <-> (a ∧ b) ∧ c
Commutativity: a ∧ b <-> b ∧ a 交换性: a ∧ b <-> b ∧ a
The Monad type class combines the operations of the Chain and Applicative type classes. Therefore, Monad instances represent type constructors which support sequential composition, and also lifting of functions of arbitrary arity. Monad 类型类结合了 Chain 和 Applicative 类型类的操作。因此, Monad 实例表示支持顺序组合以及任意数量函数提升的类型构造函数。
Instances must satisfy the following laws in addition to the Applicative and Chain laws: 除了 Applicative 和 Chain 法则之外,实例还必须满足以下法则:
The MonadThrow type class represents those monads which support errors via throwError, where throwError(e) halts, yielding the error e. MonadThrow 类型类表示那些通过 throwError 支持错误的 monad,其中 throwError(e) 停止,产生错误 e 。
This empty value should be an identity for the concat operation, which means the following equalities hold for any choice of x. 此 empty 值应该是 concat 操作的标识,这意味着以下等式适用于 x 的任何选择。
concat(x,empty)=concat(empty,x)=x
Many types that form a Semigroup also form a Monoid, such as numbers (with 0) and strings (with ''). 许多形成 Semigroup 的类型也形成 Monoid ,例如 number s(与 0 )和 string s(与 '' )。
A natural transformation is a mapping between type constructors of kind * -> * where the mapping operation has no ability to manipulate the inner values. 自然转换是 * -> * 类型构造函数之间的映射,其中映射操作无法操作内部值。
The definition of a natural transformation in category theory states that F and G should be functors, but the Functor constraint is not enforced here; that the types are of kind * -> * is enough for our purposes. 范畴论中自然变换的定义规定 F 和 G 应该是函子,但这里不强制执行 Functor 约束;对于我们的目的来说,类型是 * -> * 就足够了。
Data structure which represents non-empty arrays. 表示非空数组的数据结构。
exporttypeNonEmptyArray<A>=Array<A>&{0:A}
Note that you don’t need any conversion, a NonEmptyArray is an Array, so all Array’s APIs can be used with a NonEmptyArray without further ado. 请注意,您不需要任何转换, NonEmptyArray 就是 Array ,因此所有 Array 的 API 都可以与 NonEmptyArray 一起使用,无需多言。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
In case of NonEmptyArray concatenates the inputs into a single array. 如果是 NonEmptyArray ,则将输入连接到单个数组中。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Splits an array into sub-non-empty-arrays stored in an object, based on the result of calling a string-returning function on each element, and grouping the results according to values returned 根据对每个元素调用 string 返回函数的结果,将数组拆分为存储在对象中的子非空数组,并根据返回的值对结果进行分组
Places an element in between members of a NonEmptyArray, then folds the results using the provided Semigroup. 将一个元素放置在 NonEmptyArray 的成员之间,然后使用提供的 Semigroup 折叠结果。
Sort the elements of a NonEmptyArray in increasing order, where elements are compared using first ords[0], then ords[1], etc… 按升序对 NonEmptyArray 的元素进行排序,其中首先使用 ords[0] 比较元素,然后使用 ords[1] 等进行比较...
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass NEA.Functor instead of NEA.nonEmptyArray (where NEA is from import NEA from 'fp-ts/NonEmptyArray') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 NEA.Functor 而不是 NEA.nonEmptyArray (其中 NEA 来自 import NEA from 'fp-ts/NonEmptyArray' )
Option<A> is a container for an optional value of type A. If the value of type A is present, the Option<A> is an instance of Some<A>, containing the present value of type A. If the value is absent, the Option<A> is an instance of None. Option<A> 是 A 类型的可选值的容器。如果存在 A 类型的值,则 Option<A> 是 Some<A> 的实例,包含 A 类型的当前值。如果该值不存在,则 Option<A> 是 None 的实例。
An option could be looked at as a collection or foldable structure with either one or zero elements. Another way to look at Option is: it represents the effect of a possibly failing computation. 选项可以被视为具有一个或零个元素的集合或可折叠结构。另一种看待 Option 的方式是:它表示可能失败的计算的影响。
Example 例子
import*asOfrom'fp-ts/Option'import{pipe}from'fp-ts/function'constdouble=(n:number):number=>n*2exportconstimperative=(as:ReadonlyArray<number>):string=>{consthead=(as:ReadonlyArray<number>):number=>{if(as.length===0){thrownewError()}returnas[0]}constinverse=(n:number):number=>{if(n===0){thrownewError()}return1/n}try{return`Result is ${inverse(double(head(as)))}`}catch(e){return'no result'}}exportconstfunctional=(as:ReadonlyArray<number>):string=>{consthead=<A>(as:ReadonlyArray<A>):O.Option<A>=>(as.length===0?O.none:O.some(as[0]))constinverse=(n:number):O.Option<number>=>(n===0?O.none:O.some(1/n))returnpipe(as,head,O.map(double),O.flatMap(inverse),O.match(()=>'no result',// onNone handler(head)=>`Result is ${head}`// onSome handler))}assert.deepStrictEqual(imperative([1,2,3]),functional([1,2,3]))assert.deepStrictEqual(imperative([]),functional([]))assert.deepStrictEqual(imperative([0]),functional([0]))
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Constructs a new Option from a nullable type. If the value is null or undefined, returns None, otherwise returns the value wrapped in a Some. 从可为 null 的类型构造一个新的 Option 。如果值为 null 或 undefined ,则返回 None ,否则返回用 Some 包装的值。
Monoid returning the left-most non-None value. If both operands are Somes then the inner values are concatenated using the provided Semigroup Monoid 返回最左边的非 None 值。如果两个操作数都是 Some s,则使用提供的 Semigroup 连接内部值
The Ord instance allows Option values to be compared with compare, whenever there is an Ord instance for the type the Option contains. 只要 Option 包含的类型存在 Ord 实例, Ord 实例就允许将 Option 值与 compare 进行比较。
None is considered to be less than any Some value. None 被认为小于任何 Some 值。
Transforms an exception into an Option. If f throws, returns None, otherwise returns the output wrapped in a Some. 将异常转换为 Option 。如果 f 抛出,则返回 None ,否则返回包装在 Some 中的输出。
Takes a (lazy) default value, a function, and an Option value, if the Option value is None the default value is returned, otherwise the function is applied to the value inside the Some and the result is returned. 接受一个(惰性)默认值、一个函数和一个 Option 值,如果 Option 值是 None 则返回默认值,否则函数将应用于 Some 内的值和结果被返回。
import{some,none,match}from'fp-ts/Option'import{pipe}from'fp-ts/function'assert.strictEqual(pipe(some(1),match(()=>'a none',(a)=>`a some containing ${a}`)),'a some containing 1')assert.strictEqual(pipe(none,match(()=>'a none',(a)=>`a some containing ${a}`)),'a none')
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass O.Functor instead of O.option (where O is from import O from 'fp-ts/Option') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 O.Functor 而不是 O.option (其中 O 来自 import O from 'fp-ts/Option' )
The Ord type class represents types which support comparisons with a total order. Ord 类型类表示支持与全序比较的类型。
Instances should satisfy the laws of total orderings: 实例应满足全序法则:
Reflexivity: S.compare(a, a) <= 0 自反性: S.compare(a, a) <= 0
Antisymmetry: if S.compare(a, b) <= 0 and S.compare(b, a) <= 0 then a <-> b 反对称:如果 S.compare(a, b) <= 0 和 S.compare(b, a) <= 0 则 a <-> b
Transitivity: if S.compare(a, b) <= 0 and S.compare(b, c) <= 0 then S.compare(a, c) <= 0 传递性:如果 S.compare(a, b) <= 0 和 S.compare(b, c) <= 0 则 S.compare(a, c) <= 0
import{sort}from'fp-ts/Array'import{contramap,reverse,getMonoid}from'fp-ts/Ord'import*asSfrom'fp-ts/string'import*asBfrom'fp-ts/boolean'import{pipe}from'fp-ts/function'import{concatAll}from'fp-ts/Monoid'import*asNfrom'fp-ts/number'interfaceUser{readonlyid:numberreadonlyname:stringreadonlyage:numberreadonlyrememberMe:boolean}constbyName=pipe(S.Ord,contramap((p:User)=>p.name))constbyAge=pipe(N.Ord,contramap((p:User)=>p.age))constbyRememberMe=pipe(B.Ord,contramap((p:User)=>p.rememberMe))constM=getMonoid<User>()constusers:Array<User>=[{id:1,name:'Guido',age:47,rememberMe:false},{id:2,name:'Guido',age:46,rememberMe:true},{id:3,name:'Giulio',age:44,rememberMe:false},{id:4,name:'Giulio',age:44,rememberMe:true},]// sort by name, then by age, then by `rememberMe`constO1=concatAll(M)([byName,byAge,byRememberMe])assert.deepStrictEqual(sort(O1)(users),[{id:3,name:'Giulio',age:44,rememberMe:false},{id:4,name:'Giulio',age:44,rememberMe:true},{id:2,name:'Guido',age:46,rememberMe:true},{id:1,name:'Guido',age:47,rememberMe:false},])// now `rememberMe = true` first, then by name, then by ageconstO2=concatAll(M)([reverse(byRememberMe),byName,byAge])assert.deepStrictEqual(sort(O2)(users),[{id:4,name:'Giulio',age:44,rememberMe:true},{id:2,name:'Guido',age:46,rememberMe:true},{id:3,name:'Giulio',age:44,rememberMe:false},{id:1,name:'Guido',age:47,rememberMe:false},])
Added in v2.4.0 v2.4.0中添加
getSemigroup 获取半群
A typical use case for the Semigroup instance of Ord is merging two or more orderings. Ord 的 Semigroup 实例的典型用例是合并两个或多个排序。
For example the following snippet builds an Ord for a type User which sorts by created date descending, and thenlastName 例如,以下代码片段为类型 User 构建一个 Ord ,该类型按 created 日期降序排序,然后按 lastName 排序
A typical use case for contramap would be like, given some User type, to construct an Ord<User>. contramap 的典型用例类似于,给定一些 User 类型,构造一个 Ord<User> 。
We can do so with a function from User -> X where X is some value that we know how to compare for ordering (meaning we have an Ord<X>) 我们可以使用 User -> X 中的函数来做到这一点,其中 X 是我们知道如何比较排序的某个值(意味着我们有一个 Ord<X> )
For example, given the following User type, there are lots of possible choices for X, but let’s say we want to sort a list of users by lastName. 例如,给定以下 User 类型, X 有很多可能的选择,但假设我们想按 lastName 对用户列表进行排序。
If we have a way of comparing lastNames for ordering (ordLastName: Ord<string>) and we know how to go from User -> string, using contramap we can do this 如果我们有一种方法比较 lastName s 的排序 ( ordLastName: Ord<string> ) 并且我们知道如何从 User -> string 开始,使用 contramap 我们可以做到这一点
Returns a random number between 0 (inclusive) and 1 (exclusive). This is a direct wrapper around JavaScript’s Math.random(). 返回 0(含)和 1(不含)之间的随机数。这是 JavaScript 的 Math.random() 的直接包装。
Signature 签名
exportdeclareconstrandom:IO<number>
Added in v2.0.0 v2.0.0 中添加
randomBool 随机布尔值
Returns a random boolean value with an equal chance of being true or false 返回一个随机布尔值,其成为 true 或 false 的机会均等
Signature 签名
exportdeclareconstrandomBool:IO<boolean>
Added in v2.0.0 v2.0.0 中添加
randomElem 随机元素
Returns a random element of a ReadonlyNonEmptyArray. 返回 ReadonlyNonEmptyArray 的随机元素。
Takes a range specified by low (the first argument) and high (the second), and returns a random integer uniformly distributed in the closed interval [low, high]. It is unspecified what happens if low > high, or if either of low or high is not an integer. 获取由 low (第一个参数)和 high (第二个参数)指定的范围,并返回在闭区间 [low, high] 中均匀分布的随机整数。未指定如果 low > high 、或者 low 或 high 不是整数会发生什么。
Returns a random number between a minimum value (inclusive) and a maximum value (exclusive). It is unspecified what happens if maximum < minimum. 返回最小值(含)和最大值(不含)之间的随机数。未指定如果 maximum < minimum 会发生什么。
The Reader monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, pass values from function to function, and execute sub-computations in a modified environment. Using Reader monad for such computations is often clearer and easier than using the State monad. Reader monad(也称为环境 monad)。表示一个计算,它可以从共享环境中读取值、在函数之间传递值以及在修改的环境中执行子计算。使用 Reader monad 进行此类计算通常比使用 State monad 更清晰、更容易。
In this example the Reader monad provides access to variable bindings. Bindings are a map of number variables. The variable count contains number of variables in the bindings. You can see how to run a Reader monad and retrieve data from it, how to access the Reader data with ask and asks. 在此示例中, Reader monad 提供对变量绑定的访问。 Bindings 是 number 变量的映射。变量计数包含绑定中变量的数量。您可以看到如何运行 Reader monad 并从中检索数据,如何使用 ask 和 asks 访问 Reader 数据。
Example 例子
import{pipe}from'fp-ts/function'import*asOfrom'fp-ts/Option'import*asRfrom'fp-ts/Reader'import*asRRfrom'fp-ts/ReadonlyRecord'interfaceBindingsextendsRR.ReadonlyRecord<string,number>{}// The Reader monad, which implements this complicated check.constisCountCorrect:R.Reader<Bindings,boolean>=pipe(R.Do,R.bind('count',()=>R.asks(lookupVar('count'))),R.bind('bindings',()=>R.ask()),R.map(({count,bindings})=>count===RR.size(bindings)))// The selector function to use with 'asks'.// Returns value of the variable with specified name.constlookupVar=(name:string)=>(bindings:Bindings):number=>pipe(bindings,RR.lookup(name),O.getOrElse(()=>0))constsampleBindings:Bindings={count:3,a:1,b:2}assert.deepStrictEqual(isCountCorrect(sampleBindings),true)
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Changes the value of the local context during the execution of the action ma (similar to Contravariant’s contramap). 在执行操作 ma 期间更改本地上下文的值(类似于 Contravariant 的 contramap )。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass R.Functor instead of R.reader (where R is from import R from 'fp-ts/Reader') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 R.Functor 而不是 R.reader (其中 R 来自 import R from 'fp-ts/Reader' )
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
The default Alt instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 Alt 实例返回最后一个错误,如果你想获取所有错误,你需要提供一种通过 Semigroup 连接它们的方法。
The default Applicative instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 Applicative 实例返回第一个错误,如果您想获取所有错误,您需要提供一种通过 Semigroup 连接它们的方法。
Returns a ReaderEither whose failure and success channels have been mapped by the specified pair of functions, f and g. 返回一个 ReaderEither ,其失败和成功通道已由指定的函数对 f 和 g 映射。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Changes the value of the local context during the execution of the action ma (similar to Contravariant’s contramap). 在执行操作 ma 期间更改本地上下文的值(类似于 Contravariant 的 contramap )。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RE.Functor instead of RE.readerEither (where R is from import R from 'fp-ts/ReaderEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RE.Functor 而不是 RE.readerEither (其中 R 来自 import R from 'fp-ts/ReaderEither' )
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{pipe}from'fp-ts/function'import*asRIOfrom'fp-ts/ReaderIO'import*asConsolefrom'fp-ts/Console'// Will produce `Hello, fp-ts` to the stdoutconsteffect=pipe(RIO.ask<string>(),RIO.tapIO((value)=>Console.log(`Hello, ${value}`)))asyncfunctiontest(){assert.deepStrictEqual(effect('fp-ts')(),'fp-ts')}test()
Added in v2.16.0 v2.16.0 中添加
tapReader 点击阅读器
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Changes the value of the local context during the execution of the action ma (similar to Contravariant’s contramap). 在执行操作 ma 期间更改本地上下文的值(类似于 Contravariant 的 contramap )。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{pipe}from'fp-ts/function'import*asRTfrom'fp-ts/ReaderTask'import*asConsolefrom'fp-ts/Console'// Will produce `Hello, fp-ts` to the stdoutconsteffect=pipe(RT.ask<string>(),RT.tapIO((value)=>Console.log(`Hello, ${value}`)))asyncfunctiontest(){assert.deepStrictEqual(awaiteffect('fp-ts')(),'fp-ts')}test()
Added in v2.16.0 v2.16.0 中添加
tapReader 点击阅读器
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Changes the value of the local context during the execution of the action ma (similar to Contravariant’s contramap). 在执行操作 ma 期间更改本地上下文的值(类似于 Contravariant 的 contramap )。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RT.Functor instead of RT.readerTaskSeq (where RT is from import RT from 'fp-ts/ReaderTask') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RT.Functor 而不是 RT.readerTaskSeq (其中 RT 来自 import RT from 'fp-ts/ReaderTask' )
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RT.Functor instead of RT.readerTask (where RT is from import RT from 'fp-ts/ReaderTask') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RT.Functor 而不是 RT.readerTask (其中 RT 来自 import RT from 'fp-ts/ReaderTask' )
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import*asRTEfrom'fp-ts/ReaderTaskEither'import*asEfrom'fp-ts/Either'import*asConsolefrom'fp-ts/Console'// Will produce `Hello, fp-ts` to the stdoutconsteffect=RTE.tapIO(RTE.ask<string>(),(value)=>Console.log(`Hello, ${value}`))asyncfunctiontest(){assert.deepStrictEqual(awaiteffect('fp-ts')(),E.of('fp-ts'))}test()
Added in v2.16.0 v2.16.0 中添加
tapReader 点击阅读器
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
The default Alt instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 Alt 实例返回最后一个错误,如果你想获取所有错误,你需要提供一种通过 Semigroup 连接它们的方法。
The default ApplicativePar instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 ApplicativePar 实例返回第一个错误,如果您想获取所有错误,您需要提供一种通过 Semigroup 连接它们的方法。
Returns a ReaderTaskEither whose failure and success channels have been mapped by the specified pair of functions, f and g. 返回一个 ReaderTaskEither ,其失败和成功通道已由指定的函数对 f 和 g 映射。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Make sure that a resource is cleaned up in the event of an exception (*). The release action is called regardless of whether the body action throws (*) or returns. 确保在发生异常时清理资源 (*)。无论主体操作是抛出 (*) 还是返回,都会调用释放操作。
Changes the value of the local context during the execution of the action ma (similar to Contravariant’s contramap). 在执行操作 ma 期间更改本地上下文的值(类似于 Contravariant 的 contramap )。
Semigroup returning the left-most Left value. If both operands are Rights then the inner values are concatenated using the provided Semigroup 半群返回最左边的 Left 值。如果两个操作数都是 Right s,则使用提供的 Semigroup 连接内部值
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RTE.Functor instead of RTE.readerTaskEitherSeq (where RTE is from import RTE from 'fp-ts/ReaderTaskEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RTE.Functor 而不是 RTE.readerTaskEitherSeq (其中 RTE 来自 import RTE from 'fp-ts/ReaderTaskEither' )
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RTE.Functor instead of RTE.readerTaskEither (where RTE is from import RTE from 'fp-ts/ReaderTaskEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RTE.Functor 而不是 RTE.readerTaskEither (其中 RTE 来自 import RTE from 'fp-ts/ReaderTaskEither' )
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
In case of ReadonlyArray concatenates the inputs into a single array. 如果是 ReadonlyArray ,则将输入连接到单个数组中。
Derives an Eq over the ReadonlyArray of a given element type from the Eq of that type. The derived Eq defines two arrays as equal if all elements of both arrays are compared equal pairwise with the given E. In case of arrays of different lengths, the result is non equality. 从给定元素类型的 Eq 派生出 Eq ,而不是该类型的 ReadonlyArray 。如果两个数组的所有元素与给定的 E 成对比较,则派生的 Eq 将两个数组定义为相等。如果数组长度不同,结果不相等。
Derives an Ord over the ReadonlyArray of a given element type from the Ord of that type. The ordering between two such arrays is equal to: the first non equal comparison of each arrays elements taken pairwise in increasing order, in case of equality over all the pairwise elements; the longest array is considered the greatest, if both arrays have the same length, the result is equality. 从给定元素类型的 Ord 派生出 Ord ,而不是该类型的 ReadonlyArray 。两个这样的数组之间的顺序等于:如果所有成对元素相等,则按升序对每个数组元素进行第一个不相等比较;最长的数组被认为是最大的,如果两个数组的长度相同,则结果相等。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
A useful recursion pattern for processing a ReadonlyArray to produce a new ReadonlyArray, often used for “chopping” up the input ReadonlyArray. Typically chop is called with some function that will consume an initial prefix of the ReadonlyArray and produce a value and the tail of the ReadonlyArray. 一种有用的递归模式,用于处理 ReadonlyArray 以生成新的 ReadonlyArray ,通常用于“切碎”输入 ReadonlyArray 。通常, chop 是通过某个函数调用的,该函数将消耗 ReadonlyArray 的初始前缀并生成一个值和 ReadonlyArray 的尾部。
Splits a ReadonlyArray into length-n pieces. The last piece will be shorter if n does not evenly divide the length of the ReadonlyArray. Note that chunksOf(n)([]) is [], not [[]]. This is intentional, and is consistent with a recursive definition of chunksOf; it satisfies the property that: 将 ReadonlyArray 分割成长度为 n 的片段。如果 n 没有平分 ReadonlyArray 的长度,那么最后一段会更短。请注意, chunksOf(n)([]) 是 [] ,而不是 [[]] 。这是故意的,并且与 chunksOf 的递归定义一致;它满足以下性质:
Creates an array of array values not included in the other given array using a Eq for equality comparisons. The order and references of result values are determined by the first array. 使用 Eq 创建不包含在其他给定数组中的数组值进行相等比较。结果值的顺序和引用由第一个数组确定。
Test if a value is a member of an array. Takes a Eq<A> as a single argument which returns the function to use to search for a value of type A in an array of type ReadonlyArray<A>. 测试一个值是否是数组的成员。将 Eq<A> 作为单个参数,该参数返回用于在 ReadonlyArray<A> 类型的数组中搜索 A 类型的值的函数。
import{findFirstMap}from'fp-ts/ReadonlyArray'import{some,none}from'fp-ts/Option'interfacePerson{readonlyname:stringreadonlyage?:number}constpersons:ReadonlyArray<Person>=[{name:'John'},{name:'Mary',age:45},{name:'Joey',age:28}]// returns the name of the first person that has an ageassert.deepStrictEqual(findFirstMap((p:Person)=>(p.age===undefined?none:some(p.name)))(persons),some('Mary'))
Added in v2.5.0 v2.5.0中添加
findIndex 查找索引
Find the first index for which a predicate holds 查找谓词所包含的第一个索引
import{findLastMap}from'fp-ts/ReadonlyArray'import{some,none}from'fp-ts/Option'interfacePerson{readonlyname:stringreadonlyage?:number}constpersons:ReadonlyArray<Person>=[{name:'John'},{name:'Mary',age:45},{name:'Joey',age:28}]// returns the name of the last person that has an ageassert.deepStrictEqual(findLastMap((p:Person)=>(p.age===undefined?none:some(p.name)))(persons),some('Joey'))
Added in v2.5.0 v2.5.0中添加
head 头
Get the first element in an array, or None if the array is empty 获取数组中的第一个元素,如果数组为空则获取 None
Places an element in between members of a ReadonlyArray, then folds the results using the provided Monoid. 将一个元素放置在 ReadonlyArray 的成员之间,然后使用提供的 Monoid 折叠结果。
Creates an array of unique values that are included in all given arrays using a Eq for equality comparisons. The order and references of result values are determined by the first array. 创建一个包含在所有给定数组中的唯一值数组,使用 Eq 进行相等比较。结果值的顺序和引用由第一个数组确定。
Apply a function to the element at the specified index, creating a new array, or returning None if the index is out of bounds 将函数应用于指定索引处的元素,创建一个新数组,或者如果索引越界则返回 None
Sort the elements of an array in increasing order, where elements are compared using first ords[0], then ords[1], etc… 按升序对数组的元素进行排序,其中首先使用 ords[0] ,然后使用 ords[1] 等比较元素......
import*asRAfrom'fp-ts/ReadonlyArray'import{pipe}from'fp-ts/function'constinput:ReadonlyArray<number>=[1,2,3]assert.deepStrictEqual(pipe(input,RA.takeLeft(2)),[1,2])// out of boundsassert.strictEqual(pipe(input,RA.takeLeft(4)),input)assert.strictEqual(pipe(input,RA.takeLeft(-1)),input)
Added in v2.5.0 v2.5.0中添加
takeLeftWhile 向左走
Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new array 计算所有元素满足指定谓词的最长初始子数组,创建一个新数组
import*asRAfrom'fp-ts/ReadonlyArray'import{pipe}from'fp-ts/function'constinput:ReadonlyArray<number>=[1,2,3]assert.deepStrictEqual(pipe(input,RA.takeRight(2)),[2,3])// out of boundsassert.strictEqual(pipe(input,RA.takeRight(4)),input)assert.strictEqual(pipe(input,RA.takeRight(-1)),input)
Takes two arrays and returns an array of corresponding pairs. If one input array is short, excess elements of the longer array are discarded 接受两个数组并返回对应对的数组。如果一个输入数组很短,则较长数组中多余的元素将被丢弃
Apply a function to pairs of elements at the same index in two arrays, collecting the results in a new array. If one input array is short, excess elements of the longer array are discarded. 将函数应用于两个数组中相同索引处的元素对,并将结果收集到新数组中。如果一个输入数组很短,则较长数组中多余的元素将被丢弃。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RA.Functor instead of RA.readonlyArray (where RA is from import RA from 'fp-ts/ReadonlyArray') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RA.Functor 而不是 RA.readonlyArray (其中 RA 来自 import RA from 'fp-ts/ReadonlyArray' )
Create a map from a foldable collection of key/value pairs, using the specified Magma to combine values for duplicate keys. 从可折叠的键/值对集合创建映射,使用指定的 Magma 来组合重复键的值。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RM.Functor instead of RM.readonlyMap (where RM is from import RM from 'fp-ts/ReadonlyMap') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RM.Functor 而不是 RM.readonlyMap (其中 RM 来自 import RM from 'fp-ts/ReadonlyMap' )
Note that you don’t need any conversion, a ReadonlyNonEmptyArray is a ReadonlyArray, so all ReadonlyArray’s APIs can be used with a ReadonlyNonEmptyArray without further ado. 请注意,您不需要任何转换, ReadonlyNonEmptyArray 就是 ReadonlyArray ,因此所有 ReadonlyArray 的 API 都可以与 ReadonlyNonEmptyArray 一起使用,无需多说。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
In case of ReadonlyNonEmptyArray concatenates the inputs into a single array. 如果是 ReadonlyNonEmptyArray ,则将输入连接到单个数组中。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
A useful recursion pattern for processing a ReadonlyNonEmptyArray to produce a new ReadonlyNonEmptyArray, often used for “chopping” up the input ReadonlyNonEmptyArray. Typically chop is called with some function that will consume an initial prefix of the ReadonlyNonEmptyArray and produce a value and the tail of the ReadonlyNonEmptyArray. 一种有用的递归模式,用于处理 ReadonlyNonEmptyArray 以生成新的 ReadonlyNonEmptyArray ,通常用于“切碎”输入 ReadonlyNonEmptyArray 。通常, chop 是通过某个函数调用的,该函数将消耗 ReadonlyNonEmptyArray 的初始前缀并生成一个值和 ReadonlyNonEmptyArray 的尾部。
Splits a ReadonlyNonEmptyArray into length-n pieces. The last piece will be shorter if n does not evenly divide the length of the ReadonlyNonEmptyArray. 将 ReadonlyNonEmptyArray 分割成长度为 n 的片段。如果 n 没有平分 ReadonlyNonEmptyArray 的长度,那么最后一段会更短。
Splits an array into sub-non-empty-arrays stored in an object, based on the result of calling a string-returning function on each element, and grouping the results according to values returned 根据对每个元素调用 string 返回函数的结果,将数组拆分为存储在对象中的子非空数组,并根据返回的值对结果进行分组
Places an element in between members of a ReadonlyNonEmptyArray, then folds the results using the provided Semigroup. 将一个元素放置在 ReadonlyNonEmptyArray 的成员之间,然后使用提供的 Semigroup 折叠结果。
Sort the elements of a ReadonlyNonEmptyArray in increasing order, where elements are compared using first ords[0], then ords[1], etc… 按升序对 ReadonlyNonEmptyArray 的元素进行排序,其中首先使用 ords[0] 比较元素,然后使用 ords[1] 等进行比较...
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RNEA.Functor instead of RNEA.readonlyNonEmptyArray (where RNEA is from import RNEA from 'fp-ts/ReadonlyNonEmptyArray') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RNEA.Functor 而不是 RNEA.readonlyNonEmptyArray (其中 RNEA 来自 import RNEA from 'fp-ts/ReadonlyNonEmptyArray' )
The ReadonlyRecord.ts module enables dealing in a functional way with Typescript’s Readonly<Record<K, T>> type. That is similar to the Record.ts module, but for a record with all properties declared as readonly. ReadonlyRecord.ts 模块能够以函数式方式处理 Typescript 的 Readonly<Record<K, T>> 类型。这与 Record.ts 模块类似,但用于所有属性声明为 readonly 的记录。
import{ReadonlyRecord,toRecord}from'fp-ts/ReadonlyRecord'constx:ReadonlyRecord<string,number>={a:1,b:2}consty:Record<string,number>=toRecord(x)assert.deepStrictEqual(x,y)y.a=5// it's ok, y is mutable
Added in v2.5.0 v2.5.0中添加
toUnfoldable 至可展开
Unfolds a ReadonlyRecord into a list of key/value pairs. 将 ReadonlyRecord 展开为键/值对列表。
Given an Unfoldable class type U such as array or readonlyArray, it uses the unfold function to create an instance of U, providing an iterating function that iterates over each key/value pair in the record sorted alphabetically by key. 给定一个 Unfoldable 类类型 U ,例如 array 或 readonlyArray ,它使用 unfold 函数创建 U 的实例,提供迭代函数来迭代记录按字母顺序按键排序。
Given a Predicate, it produces a new ReadonlyRecord keeping only the entries with a value that satisfies the provided predicate. 给定一个 Predicate ,它会生成一个新的 ReadonlyRecord ,仅保留具有满足所提供谓词的值的条目。
Maps a ReadonlyRecord with an iterating function that returns an Option and it keeps only the Some values discarding the Nones. 使用返回 Option 的迭代函数映射 ReadonlyRecord ,并且仅保留 Some 值并丢弃 None 。
import{filterMap}from'fp-ts/ReadonlyRecord'import{option}from'fp-ts'constf=(s:string)=>(s.length<4?option.some(`${s} is short`):option.none)assert.deepStrictEqual(filterMap(f)({a:'foo',b:'bar',c:'verylong'}),{a:'foo is short',b:'bar is short',})
Maps a ReadonlyRecord with a function returning an Either and partitions the resulting ReadonlyRecord into Lefts and Rights. 将 ReadonlyRecord 映射到返回 Either 的函数,并将生成的 ReadonlyRecord 划分为 Left 和 Right 。
import{partitionMap}from'fp-ts/ReadonlyRecord'import{either}from'fp-ts'constf=(s:string)=>(s.length<4?either.right(`${s} is short`):either.left(`${s} is not short`))assert.deepStrictEqual(partitionMap(f)({a:'foo',b:'bar',c:'verylong'}),{left:{c:'verylong is not short',},right:{a:'foo is short',b:'bar is short',},})
Added in v2.5.0 v2.5.0中添加
separate 分离
Separate a ReadonlyRecord of Eithers into Lefts and Rights. 将 Either 中的 ReadonlyRecord 分成 Left 和 Right 。
Map and fold a ReadonlyRecord. Map the ReadonlyRecord passing each value to the iterating function. Then fold the results using the provided Monoid. 映射并折叠 ReadonlyRecord 。映射 ReadonlyRecord 将每个值传递给迭代函数。然后使用提供的 Monoid 折叠结果。
Produces a Foldable instance for a ReadonlyRecord, using the provided Ord to sort the ReadonlyRecord’s entries by key. 为 ReadonlyRecord 生成一个 Foldable 实例,使用提供的 Ord 按键对 ReadonlyRecord 的条目进行排序。
Produces a FoldableWithIndex1 instance for a ReadonlyRecord, using the provided Ord to sort the ReadonlyRecord’s entries by key. 为 ReadonlyRecord 生成一个 FoldableWithIndex1 实例,使用提供的 Ord 按键对 ReadonlyRecord 的条目进行排序。
Reduces a ReadonlyRecord passing each value to the iterating function. Entries are processed in order, sorted by key according to the given Ord. 减少将每个值传递给迭代函数的 ReadonlyRecord 。条目按顺序处理,根据给定的 Ord 按键排序。
Same as reduce but entries are processed from the right, i.e. in reverse order, from the last to the first entry, according to the given Ord. 与 reduce 相同,但根据给定的 Ord ,从右侧开始处理条目,即以相反的顺序,从最后一个条目到第一个条目。
Produces a Magma with a concat function that combines two ReadonlyRecords by making the difference. 使用 concat 函数生成 Magma ,该函数通过创建 difference 来组合两个 ReadonlyRecord 。
Given a Semigroup in the base type, it produces a Semigroup in the ReadonlyRecord of the base type. The resulting Semigroup concatenates two ReadonlyRecords by intersection. 给定基类型中的 Semigroup ,它会在基类型的 ReadonlyRecord 中生成 Semigroup 。生成的 Semigroup 通过 intersection 连接两个 ReadonlyRecord 。
Returns a Monoid instance for ReadonlyRecords, given a Semigroup instance for the base type. The Monoid makes the union of two ReadonlyRecords comining the overlapping entries with the provided Semigroup. 给定基本类型的 Semigroup 实例,返回 ReadonlyRecord s 的 Monoid 实例。 Monoid 将两个 ReadonlyRecord 进行并集,将重叠条目与提供的 Semigroup 相结合。
Produces a Show for a ReadonlyRecord, given a Show for the base type (a Show produces a human-readable representation of an instance). ReadonlyRecord entries are sorted by key with the provided Ord. 为 ReadonlyRecord 生成 Show ,给定基本类型 Show ( Show 生成实例的人类可读表示)。 ReadonlyRecord 条目使用提供的 Ord 按键排序。
Same as getMonoid. Returns a Monoid instance for ReadonlyRecords given a Semigroup instance for the base type. The Monoid makes the union of two ReadonlyRecords combining the entries that have the same key with the provided Semigroup. 与 getMonoid 相同。给定基本类型的 Semigroup 实例,返回 ReadonlyRecord 的 Monoid 实例。 Monoid 将两个 ReadonlyRecord 进行并集,将具有相同键的条目与提供的 Semigroup 组合起来。
Given a Semigroup in the base type, it produces a Semigroup in the ReadonlyRecord of the base type. The resulting Semigroup concatenates two ReadonlyRecords by union. 给定基类型中的 Semigroup ,它会在基类型的 ReadonlyRecord 中生成 Semigroup 。生成的 Semigroup 通过 union 连接两个 ReadonlyRecord 。
Takes a value and a ReadonlyRecord of functions and returns a ReadonlyRecord by applying each function to the input value. 获取一个值和一个 ReadonlyRecord 函数,并通过将每个函数应用于输入值来返回一个 ReadonlyRecord 。
import{flap}from'fp-ts/ReadonlyRecord'constfab={x:(n:number)=>`${n} times 2`,y:(n:number)=>`${n*2}`}assert.deepStrictEqual(flap(3)(fab),{x:'3 times 2',y:'6',})
Produces a Traversable instance for a ReadonlyRecord, using the provided Ord to sort the ReadonlyRecord’s entries by key. 为 ReadonlyRecord 生成一个 Traversable 实例,使用提供的 Ord 按键对 ReadonlyRecord 的条目进行排序。
Produces a TraversableWithIndex instance for a ReadonlyRecord, using the provided Ord to sort the ReadonlyRecord’s entries by key. 为 ReadonlyRecord 生成一个 TraversableWithIndex 实例,使用提供的 Ord 按键对 ReadonlyRecord 的条目进行排序。
Difference between two ReadonlyRecords. Takes two ReadonlyRecords and produces a ReadonlyRecord composed by the entries of the two inputs, removing the entries with the same key in both inputs. 两个 ReadonlyRecord 之间的差异。获取两个 ReadonlyRecord 并生成由两个输入的条目组成的 ReadonlyRecord ,删除两个输入中具有相同键的条目。
Maps a ReadonlyRecord with an iterating function that takes key and value and returns an Option, keeping only the Some values and discarding Nones. 使用迭代函数映射 ReadonlyRecord ,该迭代函数接受键和值并返回 Option ,仅保留 Some 值并丢弃 None 。
Produce a new ReadonlyRecord keeping only the entries that satisfy a predicate taking key and value as input. 生成一个新的 ReadonlyRecord ,仅保留满足以键和值作为输入的谓词的条目。
Map and fold a ReadonlyRecord. Map the ReadonlyRecord passing each key/value pair to the iterating function. Then fold the results using the provided Monoid. 映射并折叠 ReadonlyRecord 。映射 ReadonlyRecord ,将每个键/值对传递给迭代函数。然后使用提供的 Monoid 折叠结果。
Create a ReadonlyRecord from a foldable collection of key/value pairs, using the specified Magma to combine values for duplicate keys. 从可折叠的键/值对集合创建 ReadonlyRecord ,使用指定的 Magma 来组合重复键的值。
Intersection of two ReadonlyRecords. Takes two ReadonlyRecords and produces a ReadonlyRecord combining only the entries of the two inputswith the same key. It uses the concat function of the provided Magma to combine the elements. 两个 ReadonlyRecord 的交集。接受两个 ReadonlyRecord 并生成一个 ReadonlyRecord ,仅组合具有相同键的两个输入的条目。它使用提供的 Magma 的 concat 函数来组合元素。
Test whether one ReadonlyRecord contains all of the keys and values contained in another ReadonlyRecord. 测试一个 ReadonlyRecord 是否包含另一个 ReadonlyRecord 中包含的所有键和值。
Maps a ReadonlyRecord with a function returning an Either and partitions the resulting ReadonlyRecord into Lefts and Rights. 将 ReadonlyRecord 映射到返回 Either 的函数,并将生成的 ReadonlyRecord 划分为 Left 和 Right 。
import{partitionMapWithIndex}from'fp-ts/ReadonlyRecord'import{either}from'fp-ts'constf=(key:string,a:number)=>a>=0?either.right(`${key} is >= 0 (${a})`):either.left(`${key} is < 0 (${a})`)assert.deepStrictEqual(partitionMapWithIndex(f)({a:-1,b:2,c:123}),{left:{a:'a is < 0 (-1)',},right:{b:'b is >= 0 (2)',c:'c is >= 0 (123)',},})
Added in v2.5.0 v2.5.0中添加
partitionWithIndex 带索引分区
Partition a ReadonlyRecord into two parts according to a predicate that takes a key and a value. 根据采用键和值的谓词将 ReadonlyRecord 分为两部分。
Delete a key and value from a ReadonlyRecord, returning the value as well as the subsequent ReadonlyRecord. 从 ReadonlyRecord 中删除键和值,返回该值以及后续的 ReadonlyRecord 。
Same as reduceWithIndex, but reduce starting from the right (i.e. in reverse order, from the last to the first entry according to the given Ord). 与 reduceWithIndex 相同,但从右侧开始减少(即按照相反的顺序,根据给定的 Ord 从最后一个条目到第一个条目)。
Reduces a ReadonlyRecord passing each key/value pair to the iterating function. Entries are processed in the order, sorted by key according to the given Ord. 减少将每个键/值对传递给迭代函数的 ReadonlyRecord 。条目按顺序处理,根据给定的 Ord 按键排序。
ReadonlyRecord sequencing, i.e., take a ReadonlyRecord in which elements are monads and return a monad of a ReadonlyRecord of the base types. The following example for instance shows sequencing a ReadonlyRecord<string, Option<number>> into an Option<ReadonlyRecord<string, number>>. ReadonlyRecord 排序,即采用 ReadonlyRecord ,其中元素是 monad,并返回 ReadonlyRecord 基本类型的 monad。例如,以下示例显示将 ReadonlyRecord<string, Option<number>> 排序为 Option<ReadonlyRecord<string, number>> 。
sequence in ReadonlyRecord is equivalent to sequenceS in Apply.ts. ReadonlyRecord 中的 sequence 相当于 Apply.ts 中的 sequenceS 。
Union of two ReadonlyRecords. Takes two ReadonlyRecords and produces a ReadonlyRecord combining all the entries of the two inputs. It uses the concat function of the provided Magma to combine the elements with the same key. 两个 ReadonlyRecord 的并集。接受两个 ReadonlyRecord 并生成一个组合两个输入的所有条目的 ReadonlyRecord 。它使用提供的 Magma 的 concat 函数来组合具有相同键的元素。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RR.Functor instead of RR.readonlyRecord (where RR is from import RR from 'fp-ts/ReadonlyRecord') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RR.Functor 而不是 RR.readonlyRecord (其中 RR 来自 import RR from 'fp-ts/ReadonlyRecord' )
Checks an element is a member of a set; If yes, removes the value from the set If no, inserts the value to the set 检查一个元素是否是集合的成员;如果是,则从集合中删除该值 如果否,则将该值插入到集合中
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass RT.Functor instead of RT.readonlyTuple (where RT is from import RT from 'fp-ts/ReadonlyTuple') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 RT.Functor 而不是 RT.readonlyTuple (其中 RT 来自 import RT from 'fp-ts/ReadonlyTuple' )
The Record module enables dealing with Typescript’s Record<K, T> type in a functional way, basically treating it as a Functor in T. Record 模块能够以函数式方式处理 Typescript 的 Record<K, T> 类型,基本上将其视为 T 中的 Functor 。
Given a Predicate, it produces a new Record keeping only the entries with a value that satisfies the provided predicate. 给定一个 Predicate ,它会生成一个新的 Record ,仅保留具有满足所提供谓词的值的条目。
Maps a Record with an iterating function that returns an Option and it keeps only the Some values discarding the Nones. 使用返回 Option 的迭代函数映射 Record ,并且仅保留 Some 值并丢弃 None 。
import{filterMap}from'fp-ts/Record'import{option}from'fp-ts'constf=(s:string)=>(s.length<4?option.some(`${s} is short`):option.none)assert.deepStrictEqual(filterMap(f)({a:'foo',b:'bar',c:'verylong'}),{a:'foo is short',b:'bar is short',})
Maps a Record with a function returning an Either and partitions the resulting Record into Lefts and Rights. 将 Record 映射到返回 Either 的函数,并将生成的 Record 划分为 Left 和 Right 。
import{partitionMap}from'fp-ts/Record'import{either}from'fp-ts'constf=(s:string)=>(s.length<4?either.right(`${s} is short`):either.left(`${s} is not short`))assert.deepStrictEqual(partitionMap(f)({a:'foo',b:'bar',c:'verylong'}),{left:{c:'verylong is not short',},right:{a:'foo is short',b:'bar is short',},})
Added in v2.0.0 v2.0.0 中添加
separate 分离
Separate a Record of Eithers into Lefts and Rights. 将 Either 中的 Record 分成 Left 和 Right 。
Map and fold a Record. Map the Record passing each value to the iterating function. Then fold the results using the provided Monoid. 映射并折叠 Record 。映射 Record 将每个值传递给迭代函数。然后使用提供的 Monoid 折叠结果。
Produces a Foldable instance for a Record, using the provided Ord to sort the Record’s entries by key. 为 Record 生成一个 Foldable 实例,使用提供的 Ord 按键对 Record 的条目进行排序。
Produces a FoldableWithIndex1 instance for a Record, using the provided Ord to sort the Record’s entries by key. 为 Record 生成一个 FoldableWithIndex1 实例,使用提供的 Ord 按键对 Record 的条目进行排序。
Reduces a Record passing each value to the iterating function. Entries are processed in order, sorted by key according to the given Ord. 减少将每个值传递给迭代函数的 Record 。条目按顺序处理,根据给定的 Ord 按键排序。
Same as reduce but entries are processed from the right, i.e. in reverse order, from the last to the first entry, according to the given Ord. 与 reduce 相同,但根据给定的 Ord ,从右侧开始处理条目,即以相反的顺序,从最后一个条目到第一个条目。
Given a Semigroup in the base type, it produces a Semigroup in the Record of the base type. The resulting Semigroup concatenates two Records by intersection. 给定基类型中的 Semigroup ,它会在基类型的 Record 中生成 Semigroup 。生成的 Semigroup 通过 intersection 连接两个 Record 。
Returns a Monoid instance for Records, given a Semigroup instance for the base type. The Monoid makes the union of two Records comining the overlapping entries with the provided Semigroup. 给定基本类型的 Semigroup 实例,返回 Record s 的 Monoid 实例。 Monoid 将两个 Record 进行并集,将重叠条目与提供的 Semigroup 相结合。
Produces a Show for a Record, given a Show for the base type (a Show produces a human-readable representation of an instance). Record entries are sorted by key with the provided Ord. 为 Record 生成 Show ,给定基本类型 Show ( Show 生成实例的人类可读表示)。 Record 条目使用提供的 Ord 按键排序。
Same as getMonoid. Returns a Monoid instance for Records given a Semigroup instance for the base type. The Monoid makes the union of two Records combining the entries that have the same key with the provided Semigroup. 与 getMonoid 相同。给定基本类型的 Semigroup 实例,返回 Record 的 Monoid 实例。 Monoid 将两个 Record 进行并集,将具有相同键的条目与提供的 Semigroup 组合起来。
Given a Semigroup in the base type, it produces a Semigroup in the Record of the base type. The resulting Semigroup concatenates two Records by union. 给定基类型中的 Semigroup ,它会在基类型的 Record 中生成 Semigroup 。生成的 Semigroup 通过 union 连接两个 Record 。
Takes a value and a Record of functions and returns a Record by applying each function to the input value. 获取一个值和一个 Record 函数,并通过将每个函数应用于输入值来返回一个 Record 。
import{flap}from'fp-ts/Record'constfab={x:(n:number)=>`${n} times 2`,y:(n:number)=>`${n*2}`}assert.deepStrictEqual(flap(3)(fab),{x:'3 times 2',y:'6',})
Added in v2.10.0 v2.10.0 中添加
map 地图
Map a Record passing the values to the iterating function. 映射 Record 将值传递给迭代函数。
Produces a Traversable instance for a Record, using the provided Ord to sort the Record’s entries by key. 为 Record 生成一个 Traversable 实例,使用提供的 Ord 按键对 Record 的条目进行排序。
Produces a TraversableWithIndex instance for a Record, using the provided Ord to sort the Record’s entries by key. 为 Record 生成一个 TraversableWithIndex 实例,使用提供的 Ord 按键对 Record 的条目进行排序。
Map a Record into an Array. It passes each key/value pair to the iterating function and collects the results in an array, sorted alphabetically by the original key. 将 Record 映射到 Array 。它将每个键/值对传递给迭代函数,并将结果收集到一个数组中,并按原始键的字母顺序排序。
Difference between two Records. Takes two Records and produces a Record composed by the entries of the two inputs, removing the entries with the same key in both inputs. 两个 Record 之间的差异。获取两个 Record 并生成由两个输入的条目组成的 Record ,删除两个输入中具有相同键的条目。
Maps a Record with an iterating function that takes key and value and returns an Option, keeping only the Some values and discarding Nones. 使用迭代函数映射 Record ,该迭代函数接受键和值并返回 Option ,仅保留 Some 值并丢弃 None 。
Map and fold a Record. Map the Record passing each key/value pair to the iterating function. Then fold the results using the provided Monoid. 映射并折叠 Record 。映射 Record ,将每个键/值对传递给迭代函数。然后使用提供的 Monoid 折叠结果。
Create a Record from a foldable collection of key/value pairs, using the specified Magma to combine values for duplicate keys. 从可折叠的键/值对集合创建 Record ,使用指定的 Magma 来组合重复键的值。
Intersection of two Records. Takes two Records and produces a Record combining only the entries of the two inputswith the same key. It uses the concat function of the provided Magma to combine the elements. 两个 Record 的交集。接受两个 Record 并生成一个 Record ,仅组合具有相同键的两个输入的条目。它使用提供的 Magma 的 concat 函数来组合元素。
Maps a Record with a function returning an Either and partitions the resulting Record into Lefts and Rights. 将 Record 映射到返回 Either 的函数,并将生成的 Record 划分为 Left 和 Right 。
import{partitionMapWithIndex}from'fp-ts/Record'import{either}from'fp-ts'constf=(key:string,a:number)=>a>=0?either.right(`${key} is >= 0 (${a})`):either.left(`${key} is < 0 (${a})`)assert.deepStrictEqual(partitionMapWithIndex(f)({a:-1,b:2,c:123}),{left:{a:'a is < 0 (-1)',},right:{b:'b is >= 0 (2)',c:'c is >= 0 (123)',},})
Added in v2.0.0 v2.0.0 中添加
partitionWithIndex 带索引分区
Partition a Record into two parts according to a predicate that takes a key and a value. 根据采用键和值的谓词将 Record 分为两部分。
Same as reduceWithIndex, but reduce starting from the right (i.e. in reverse order, from the last to the first entry according to the given Ord). 与 reduceWithIndex 相同,但从右侧开始减少(即按照相反的顺序,根据给定的 Ord 从最后一个条目到第一个条目)。
Reduces a Record passing each key/value pair to the iterating function. Entries are processed in the order, sorted by key according to the given Ord. 减少将每个键/值对传递给迭代函数的 Record 。条目按顺序处理,根据给定的 Ord 按键排序。
Record sequencing, i.e., take a Record in which elements are monads and return a monad of a Record of the base types. The following example for instance shows sequencing a Record<string, Option<number>> into an Option<Record<string, number>>. Record 排序,即采用 Record ,其中元素是 monad,并返回 Record 基本类型的 monad。例如,以下示例显示将 Record<string, Option<number>> 排序为 Option<Record<string, number>> 。
sequence in Record is equivalent to sequenceS in Apply.ts. Record 中的 sequence 相当于 Apply.ts 中的 sequenceS 。
Unfolds a Record into a list of key/value pairs. 将 Record 展开为键/值对列表。
Given an Unfoldable class type U such as array or readonlyArray, it uses the unfold function to create an instance of U, providing an iterating function that iterates over each key/value pair in the record sorted alphabetically by key. 给定一个 Unfoldable 类类型 U ,例如 array 或 readonlyArray ,它使用 unfold 函数创建 U 的实例,提供迭代函数来迭代记录按字母顺序按键排序。
Union of two Records. Takes two Records and produces a Record combining all the entries of the two inputs. It uses the concat function of the provided Magma to combine the elements with the same key. 两个 Record 的并集。接受两个 Record 并生成一个组合两个输入的所有条目的 Record 。它使用提供的 Magma 的 concat 函数来组合具有相同键的元素。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass R.Functor instead of R.record (where R is from import R from 'fp-ts/Record') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 R.Functor 而不是 R.record (其中 R 来自 import R from 'fp-ts/Record' )
Returns a Refinement from a Option returning function. This function ensures that a Refinement definition is type-safe. 从 Option 返回函数返回 Refinement 。此函数确保 Refinement 定义是类型安全的。
The Ring class is for types that support addition, multiplication, and subtraction operations. Ring 类适用于支持加法、乘法和减法运算的类型。
Instances must satisfy the following law in addition to the Semiring laws: 除了 Semiring 法则之外,实例还必须满足以下法则:
Additive inverse: a - a <-> (zero - a) + a <-> zero 加法逆: a - a <-> (zero - a) + a <-> zero
Adapted from https://github.com/purescript/purescript-prelude/blob/master/src/Data/Ring.purs 改编自https://github.com/purescript/purescript-prelude/blob/master/src/Data/Ring.purs
The Semiring class is for types that support an addition and multiplication operation. Semiring 类适用于支持加法和乘法运算的类型。
Instances must satisfy the following laws: 实例必须满足以下定律:
Commutative monoid under addition: 加法下的交换幺半群:
Associativity: (a + b) + c <-> a + (b + c) 关联性: (a + b) + c <-> a + (b + c)
Identity: zero + a = a + zero <-> a 身份: zero + a = a + zero <-> a
Commutative: a + b <-> b + a 可交换: a + b <-> b + a
Monoid under multiplication: 乘法下的幺半群:
Associativity: (a * b) * c <-> a * (b * c) 关联性: (a * b) * c <-> a * (b * c)
Identity: one * a <-> a * one <-> a 身份: one * a <-> a * one <-> a
Multiplication distributes over addition: 乘法分布于加法:
Left distributivity: a * (b + c) <-> (a * b) + (a * c) 左分配率: a * (b + c) <-> (a * b) + (a * c)
Right distributivity: (a + b) * c <-> (a * c) + (b * c) 右分布性: (a + b) * c <-> (a * c) + (b * c)
Annihilation: zero * a <-> a * zero <-> zero 湮灭: zero * a <-> a * zero <-> zero
Note: The number type is not fully law abiding members of this class hierarchy due to the potential for arithmetic overflows, and the presence of NaN and Infinity values. The behaviour is unspecified in these cases. 注意:由于存在算术溢出的可能性以及 NaN 和 Infinity 值的存在, number 类型不是此类层次结构中完全守法的成员。在这些情况下,行为未指定。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Checks an element is a member of a set; If yes, removes the value from the set If no, inserts the value to the set 检查一个元素是否是集合的成员;如果是,则从集合中删除该值 如果否,则将该值插入到集合中
The Show type class represents those types which can be converted into a human-readable string representation. Show 类型类表示可以转换为人类可读的 string 表示形式的类型。
While not required, it is recommended that for any expression x, the string show(x) be executable TypeScript code which evaluates to the same value as the expression x. 虽然不是必需的,但建议对于任何表达式 x ,字符串 show(x) 是可执行的 TypeScript 代码,其计算结果与表达式 x 的值相同。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass S.Functor instead of S.state (where S is from import S from 'fp-ts/State') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 S.Functor 而不是 S.state (其中 S 来自 import S from 'fp-ts/State' )
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Changes the value of the local context during the execution of the action ma (similar to Contravariant’s contramap). 在执行操作 ma 期间更改本地上下文的值(类似于 Contravariant 的 contramap )。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass SRTE.Functor instead of SRTE.stateReaderTaskEitherSeq (where SRTE is from import SRTE from 'fp-ts/StateReaderTaskEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 SRTE.Functor 而不是 SRTE.stateReaderTaskEitherSeq (其中 SRTE 来自 import SRTE from 'fp-ts/StateReaderTaskEither' )
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass SRTE.Functor instead of SRTE.stateReaderTaskEither (where SRTE is from import SRTE from 'fp-ts/StateReaderTaskEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 SRTE.Functor 而不是 SRTE.stateReaderTaskEither (其中 SRTE 来自 import SRTE from 'fp-ts/StateReaderTaskEither' )
The state monad transformer. It can be used to add state to other monads. 状态单子变压器。它可用于向其他 monad 添加状态。
The of function leaves the state unchanged, while chain uses the final state of the first computation as the initial state of the second. of 函数保持状态不变,而 chain 使用第一次计算的最终状态作为第二次计算的初始状态。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Comonad instance, pass S.Comonad instead of S.store (where S is from import S from 'fp-ts/Store') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Comonad 实例,请传递 S.Comonad 而不是 S.store (其中 S 来自 import S from 'fp-ts/Store' )
import*asSfrom'fp-ts/string'import{pipe}from'fp-ts/function'assert.deepStrictEqual(pipe(' a ',S.trim),'a')
Added in v2.11.0 v2.11.0 中添加
trimLeft 向左修剪
Signature 签名
exportdeclareconsttrimLeft:(s:string)=>string
Example 例子
import*asSfrom'fp-ts/string'import{pipe}from'fp-ts/function'assert.deepStrictEqual(pipe(' a ',S.trimLeft),'a ')
Added in v2.11.0 v2.11.0 中添加
trimRight 右修剪
Signature 签名
exportdeclareconsttrimRight:(s:string)=>string
Example 例子
import*asSfrom'fp-ts/string'import{pipe}from'fp-ts/function'assert.deepStrictEqual(pipe(' a ',S.trimRight),' a')
Added in v2.11.0 v2.11.0 中添加
Strong overview 强概览
The Strong class extends Profunctor with combinators for working with product types. Strong 类使用组合器扩展了 Profunctor ,以处理产品类型。
first and second lift values in a Profunctor to act on the first and second components of a tuple, respectively. first 和 second 提升 Profunctor 中的值,分别作用于元组的第一个和第二个组件。
Another way to think about Strong is to piggyback on the intuition of inputs and outputs. Rewriting the type signature in this light then yields: 思考 Strong 的另一种方式是依靠输入和输出的直觉。从这个角度重写类型签名会产生:
first :: forall input output a. p input output -> p (Tuple input a) (Tuple output a)
second :: forall input output a. p input output -> p (Tuple a input) (Tuple a output)
If we specialize the profunctor p to the function arrow, we get the following type signatures, which may look a bit more familiar: 如果我们将函子 p 专门化为函数箭头,我们会得到以下类型签名,这可能看起来更熟悉一些:
first :: forall input output a. (input -> output) -> (Tuple input a) -> (Tuple output a)
second :: forall input output a. (input -> output) -> (Tuple a input) -> (Tuple a output)
So, when the profunctor is Function application, first essentially applies your function to the first element of a tuple, and second applies it to the second element (same as map would do). 因此,当 profunctor 是 Function 应用程序时, first 本质上将您的函数应用于元组的第一个元素, second 将其应用于第二个元素(与 map 的操作相同)。
Adapted from https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Strong.purs 改编自https://github.com/purescript/purescript-profunctor/blob/master/src/Data/Profunctor/Strong.purs
Compose a value which introduces a tuple from two values, each introducing one side of the tuple. 组成一个由两个值引入元组的值,每个值引入元组的一侧。
This combinator is useful when assembling values from smaller components, because it provides a way to support two different types of output. 当从较小的组件组装值时,此组合器非常有用,因为它提供了一种支持两种不同类型输出的方法。
Specializing fanOut to function application would look like this: 将 fanOut 专门化为函数应用程序将如下所示:
fanOut :: forall a b c. (a -> b) -> (a -> c) -> (a -> (Tuple b c))
We take two functions, f and g, with the same parameter type and we transform them into a single function which takes one parameter and returns a tuple of the results of running f and g on the parameter, respectively. This allows us to run two parallel computations on the same input and return both results in a tuple. 我们采用两个具有相同参数类型的函数 f 和 g ,并将它们转换为单个函数,该函数采用一个参数并返回在参数上运行 f 和 g 结果的元组,分别。这允许我们对同一输入运行两个并行计算,并以元组形式返回两个结果。
Compose a value acting on a tuple from two values, each acting on one of the components of the tuple. 由两个值组成一个作用于元组的值,每个值作用于元组的一个组件。
Specializing split to function application would look like this: 将 split 专门化为函数应用程序将如下所示:
split :: forall a b c d. (a -> b) -> (c -> d) -> (Tuple a c) -> (Tuple b d)
We take two functions, f and g, and we transform them into a single function which takes a tuple and maps f over the first element and g over the second. Just like bi-map would do for the bi-functor instance of tuple. 我们采用两个函数 f 和 g ,并将它们转换为单个函数,该函数采用一个元组并将 f 映射到第一个元素,将 g 映射到第二个元素。就像 bi-map 对元组的 bi-functor 实例所做的那样。
Task<A> represents an asynchronous computation that yields a value of type A and never fails. If you want to represent an asynchronous computation that may fail, please see TaskEither. Task<A> 表示异步计算,产生 A 类型的值并且永远不会失败。如果你想表示一个可能失败的异步计算,请参见 TaskEither 。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{pipe}from'fp-ts/function'import*asTfrom'fp-ts/Task'import*asConsolefrom'fp-ts/Console'// Will produce `Hello, fp-ts` to the stdoutconsteffect=pipe(T.of('fp-ts'),T.tapIO((value)=>Console.log(`Hello, ${value}`)))asyncfunctiontest(){assert.deepStrictEqual(awaiteffect(),'fp-ts')}test()
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass T.Functor instead of T.taskSeq (where T is from import T from 'fp-ts/Task') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 T.Functor 而不是 T.taskSeq (其中 T 来自 import T from 'fp-ts/Task' )
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass T.Functor instead of T.task (where T is from import T from 'fp-ts/Task') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 T.Functor 而不是 T.task (其中 T 来自 import T from 'fp-ts/Task' )
TaskEither<E, A> represents an asynchronous computation that either yields a value of type A or fails yielding an error of type E. If you want to represent an asynchronous computation that never fails, please see Task. TaskEither<E, A> 表示异步计算,它要么生成 A 类型的值,要么失败并生成 E 类型的错误。如果你想表示一个永不失败的异步计算,请参阅 Task 。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{pipe}from'fp-ts/function'import*asTEfrom'fp-ts/TaskEither'import*asEfrom'fp-ts/Either'import*asConsolefrom'fp-ts/Console'// Will produce `Hello, fp-ts` to the stdoutconsteffectA=TE.tapIO(TE.of(1),(value)=>Console.log(`Hello, ${value}`))// No output to the stdoutconsteffectB=pipe(TE.left('error'),TE.tapIO((value)=>Console.log(`Hello, ${value}`)))asyncfunctiontest(){assert.deepStrictEqual(awaiteffectA(),E.of(1))assert.deepStrictEqual(awaiteffectB(),E.left('error'))}test()
Added in v2.16.0 v2.16.0 中添加
tapTask 点击任务
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Identifies an associative operation on a type constructor. It is similar to Semigroup, except that it applies to types of kind * -> *. 标识类型构造函数上的关联操作。它与 Semigroup 类似,但它适用于 * -> * 类型。
In case of TaskEither returns fa if is a Right or the value returned by that otherwise. 如果是 TaskEither ,则返回 fa (如果是 Right ),否则返回 that 返回的值。
The default Alt instance returns the last error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 Alt 实例返回最后一个错误,如果你想获取所有错误,你需要提供一种通过 Semigroup 连接它们的方法。
The default ApplicativePar instance returns the first error, if you want to get all errors you need to provide a way to concatenate them via a Semigroup. 默认的 ApplicativePar 实例返回第一个错误,如果您想获取所有错误,您需要提供一种通过 Semigroup 连接它们的方法。
import*asEfrom'fp-ts/Either'import{pipe}from'fp-ts/function'import*asRAfrom'fp-ts/ReadonlyArray'import*asSfrom'fp-ts/Semigroup'import*asstringfrom'fp-ts/string'import*asTfrom'fp-ts/Task'import*asTEfrom'fp-ts/TaskEither'interfaceUser{readonlyid:stringreadonlyname:string}constremoteDatabase:ReadonlyArray<User>=[{id:'id1',name:'John'},{id:'id2',name:'Mary'},{id:'id3',name:'Joey'},]constfetchUser=(id:string):TE.TaskEither<string,User>=>pipe(remoteDatabase,RA.findFirst((user)=>user.id===id),TE.fromOption(()=>`${id} not found`))asyncfunctiontest(){assert.deepStrictEqual(awaitpipe(['id4','id5'],RA.traverse(TE.ApplicativePar)(fetchUser))(),E.left('id4 not found')// <= first error)constApplicative=TE.getApplicativeTaskValidation(T.ApplyPar,pipe(string.Semigroup,S.intercalate(', ')))assert.deepStrictEqual(awaitpipe(['id4','id5'],RA.traverse(Applicative)(fetchUser))(),E.left('id4 not found, id5 not found')// <= all errors)}test()
Returns a TaskEither whose failure and success channels have been mapped by the specified pair of functions, f and g. 返回一个 TaskEither ,其失败和成功通道已由指定的函数对 f 和 g 映射。
import*asEfrom'fp-ts/Either'import{pipe}from'fp-ts/function'import*asTEfrom'fp-ts/TaskEither'asyncfunctiontest(){consterrorHandler=TE.orElse((error:string)=>TE.right(`recovering from ${error}...`))assert.deepStrictEqual(awaitpipe(TE.right('ok'),errorHandler)(),E.right('ok'))assert.deepStrictEqual(awaitpipe(TE.left('ko'),errorHandler)(),E.right('recovering from ko...'))}test()
Convert a node style callback function to one returning a TaskEither 将节点样式回调函数转换为返回 TaskEither 的回调函数
Note. If the function f admits multiple overloadings, taskify will pick last one. If you want a different behaviour, add an explicit type annotation 笔记。如果函数 f 允许多个重载, taskify 将选择最后一个。如果您想要不同的行为,请添加显式类型注释
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Make sure that a resource is cleaned up in the event of an exception (*). The release action is called regardless of whether the body action throws (*) or returns. 确保在发生异常时清理资源 (*)。无论主体操作是抛出 (*) 还是返回,都会调用释放操作。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass TE.Functor instead of TE.taskEitherSeq (where TE is from import TE from 'fp-ts/TaskEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 TE.Functor 而不是 TE.taskEitherSeq (其中 TE 来自 import TE from 'fp-ts/TaskEither' )
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass TE.Functor instead of TE.taskEither (where TE is from import TE from 'fp-ts/TaskEither') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 TE.Functor 而不是 TE.taskEither (其中 TE 来自 import TE from 'fp-ts/TaskEither' )
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{pipe}from'fp-ts/function'import*asTOfrom'fp-ts/TaskOption'import*asOfrom'fp-ts/Option'import*asConsolefrom'fp-ts/Console'// Will produce `Hello, fp-ts` to the stdoutconsteffectA=TO.tapIO(TO.of(1),(value)=>Console.log(`Hello, ${value}`))// No output to the stdoutconsteffectB=pipe(TO.noneasTO.TaskOption<string>,TO.tapIO((value)=>Console.log(`Hello, ${value}`)))asyncfunctiontest(){assert.deepStrictEqual(awaiteffectA(),O.of(1))assert.deepStrictEqual(awaiteffectB(),O.none)}test()
Added in v2.16.0 v2.16.0 中添加
tapTask 点击任务
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass TT.Functor instead of TT.taskThese (where TT is from import TT from 'fp-ts/TaskThese') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 TT.Functor 而不是 TT.taskThese (其中 TT 来自 import TT from 'fp-ts/TaskThese' )
A data structure providing “inclusive-or” as opposed to Either’s “exclusive-or”. 提供“包含或”而不是 Either 的“异或”的数据结构。
If you interpret Either<E, A> as suggesting the computation may either fail or succeed (exclusively), then These<E, A> may fail, succeed, or do both at the same time. 如果您将 Either<E, A> 解释为表明计算可能失败或成功(仅),则 These<E, A> 可能会失败、成功或同时执行两者。
There are a few ways to interpret the both case: 有几种方法可以解释这两种情况:
You can think of a computation that has a non-fatal error. 您可以想象一个存在非致命错误的计算。
You can think of a computation that went as far as it could before erroring. 您可以想象在出错之前尽可能进行的计算。
You can think of a computation that keeps track of errors as it completes. 您可以想象一种在完成时跟踪错误的计算。
Another way you can think of These<E, A> is saying that we want to handle E kind of data, A kind of data, or both E and A kind of data at the same time. This is particularly useful when it comes to displaying UI’s. 您可以想到 These<E, A> 的另一种方式是说我们想要处理 E 类型的数据、 A 类型的数据、或者同时处理 E 和 A 类型的数据。这在显示 UI 时特别有用。
(description adapted from https://package.elm-lang.org/packages/joneshf/elm-these) (描述改编自https://package.elm-lang.org/packages/joneshf/elm-these)
Adapted from https://github.com/purescript-contrib/purescript-these 改编自 https://github.com/purescript-contrib/purescript-these
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass T.Functor instead of T.these (where T is from import T from 'fp-ts/These') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 T.Functor 而不是 T.these (其中 T 来自 import T from 'fp-ts/These' )
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Traversable represents data structures which can be traversed accumulating results and effects in some Applicative functor. Traversable 表示可以遍历的数据结构,在某些 Applicative 函子中累积结果和效果。
traverse runs an action for every element in a data structure, and accumulates the results. traverse 对数据结构中的每个元素运行一个操作,并累积结果。
sequence runs the actions contained in a data structure, and accumulates the results. sequence 运行数据结构中包含的操作,并累积结果。
The traverse and sequence functions should be compatible in the following sense: traverse 和 sequence 函数应该在以下意义上兼容:
traverse(A)(xs, f) <-> sequence(A)(A.map(xs, f))
sequence(A)(xs) <-> traverse(A)(xs, identity)
where A is an Applicative instance 其中 A 是 Applicative 实例
Traversable instances should also be compatible with the corresponding Foldable instances, in the following sense: Traversable 实例也应该与相应的 Foldable 实例兼容,在以下意义上:
exportinterfaceTraversable<T>extendsFunctor<T>,Foldable<T>{/**
* Runs an action for every element in a data structure and accumulates the results
*/readonlytraverse:Traverse<T>readonlysequence:Sequence<T>}
A Traversable with an additional index. A TraversableWithIndex instance must be compatible with its Traversable instance 带有附加索引的 Traversable 。 TraversableWithIndex 实例必须与其 Traversable 实例兼容
import{fold,make}from'fp-ts/Tree'import{concatAll}from'fp-ts/Monoid'import{MonoidSum}from'fp-ts/number'constt=make(1,[make(2),make(3)])constsum=concatAll(MonoidSum)// Sum the values in a tree:assert.deepStrictEqual(fold((a:number,bs:Array<number>)=>a+sum(bs))(t),6)// Find the maximum value in the tree:assert.deepStrictEqual(fold((a:number,bs:Array<number>)=>bs.reduce((b,acc)=>Math.max(b,acc),a))(t),3)// Count the number of leaves in the tree:assert.deepStrictEqual(fold((_:number,bs:Array<number>)=>(bs.length===0?1:sum(bs)))(t),2)
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。
Composes computations in sequence, using the return value of one computation to determine the next computation and keeping only the result of the first. 按顺序组成计算,使用一个计算的返回值来确定下一个计算并仅保留第一个计算的结果。
import{make,drawTree}from'fp-ts/Tree'constfa=make('a',[make('b'),make('c'),make('d',[make('e'),make('f')])])assert.strictEqual(drawTree(fa),`a
├─ b
├─ c
└─ d
├─ e
└─ f`)
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass T.Functor instead of T.tree (where T is from import T from 'fp-ts/Tree') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 T.Functor 而不是 T.tree (其中 T 来自 import T from 'fp-ts/Tree' )
This instance is deprecated, use small, specific instances instead. For example if a function needs a Functor instance, pass T.Functor instead of T.tuple (where T is from import T from 'fp-ts/Tuple') 此实例已弃用,请改用小型特定实例。例如,如果函数需要 Functor 实例,请传递 T.Functor 而不是 T.tuple (其中 T 来自 import T from 'fp-ts/Tuple' )
Witherable represents data structures which can be partitioned with effects in some Applicative functor. Witherable 表示可以在某些 Applicative 函子中使用效果进行分区的数据结构。
Adapted from https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Witherable.purs 改编自https://github.com/LiamGoodacre/purescript-filterable/blob/master/src/Data/Witherable.purs
exportinterfaceWitherable<T>extendsTraversable<T>,Filterable<T>{/**
* Partition a structure with effects
*/readonlywilt:Wilt<T>/**
* Filter a structure with effects
*/readonlywither:Wither<T>}
map can be used to turn functions (a: A) => B into functions (fa: F<A>) => F<B> whose argument and return types use the type constructor F to represent some computational context. map 可用于将函数 (a: A) => B 转换为函数 (fa: F<A>) => F<B> ,其参数和返回类型使用类型构造函数 F 来表示某些计算上下文。